Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
mmdetection | mmdetection-master/tools/deployment/pytorch2onnx.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import warnings
from functools import partial
import numpy as np
import onnx
import torch
from mmcv import Config, DictAction
from mmdet.core.export import build_model_from_cfg, preprocess_example_input
from mmdet.core.export.model_wrappers import ONNXRuntimeDetector
def pytorch2onnx(model,
input_img,
input_shape,
normalize_cfg,
opset_version=11,
show=False,
output_file='tmp.onnx',
verify=False,
test_img=None,
do_simplify=False,
dynamic_export=None,
skip_postprocess=False):
input_config = {
'input_shape': input_shape,
'input_path': input_img,
'normalize_cfg': normalize_cfg
}
# prepare input
one_img, one_meta = preprocess_example_input(input_config)
img_list, img_meta_list = [one_img], [[one_meta]]
if skip_postprocess:
warnings.warn('Not all models support export onnx without post '
'process, especially two stage detectors!')
model.forward = model.forward_dummy
torch.onnx.export(
model,
one_img,
output_file,
input_names=['input'],
export_params=True,
keep_initializers_as_inputs=True,
do_constant_folding=True,
verbose=show,
opset_version=opset_version)
print(f'Successfully exported ONNX model without '
f'post process: {output_file}')
return
# replace original forward function
origin_forward = model.forward
model.forward = partial(
model.forward,
img_metas=img_meta_list,
return_loss=False,
rescale=False)
output_names = ['dets', 'labels']
if model.with_mask:
output_names.append('masks')
input_name = 'input'
dynamic_axes = None
if dynamic_export:
dynamic_axes = {
input_name: {
0: 'batch',
2: 'height',
3: 'width'
},
'dets': {
0: 'batch',
1: 'num_dets',
},
'labels': {
0: 'batch',
1: 'num_dets',
},
}
if model.with_mask:
dynamic_axes['masks'] = {0: 'batch', 1: 'num_dets'}
torch.onnx.export(
model,
img_list,
output_file,
input_names=[input_name],
output_names=output_names,
export_params=True,
keep_initializers_as_inputs=True,
do_constant_folding=True,
verbose=show,
opset_version=opset_version,
dynamic_axes=dynamic_axes)
model.forward = origin_forward
if do_simplify:
import onnxsim
from mmdet import digit_version
min_required_version = '0.4.0'
assert digit_version(onnxsim.__version__) >= digit_version(
min_required_version
), f'Requires to install onnxsim>={min_required_version}'
model_opt, check_ok = onnxsim.simplify(output_file)
if check_ok:
onnx.save(model_opt, output_file)
print(f'Successfully simplified ONNX model: {output_file}')
else:
warnings.warn('Failed to simplify ONNX model.')
print(f'Successfully exported ONNX model: {output_file}')
if verify:
# check by onnx
onnx_model = onnx.load(output_file)
onnx.checker.check_model(onnx_model)
# wrap onnx model
onnx_model = ONNXRuntimeDetector(output_file, model.CLASSES, 0)
if dynamic_export:
# scale up to test dynamic shape
h, w = [int((_ * 1.5) // 32 * 32) for _ in input_shape[2:]]
h, w = min(1344, h), min(1344, w)
input_config['input_shape'] = (1, 3, h, w)
if test_img is None:
input_config['input_path'] = input_img
# prepare input once again
one_img, one_meta = preprocess_example_input(input_config)
img_list, img_meta_list = [one_img], [[one_meta]]
# get pytorch output
with torch.no_grad():
pytorch_results = model(
img_list,
img_metas=img_meta_list,
return_loss=False,
rescale=True)[0]
img_list = [_.cuda().contiguous() for _ in img_list]
if dynamic_export:
img_list = img_list + [_.flip(-1).contiguous() for _ in img_list]
img_meta_list = img_meta_list * 2
# get onnx output
onnx_results = onnx_model(
img_list, img_metas=img_meta_list, return_loss=False)[0]
# visualize predictions
score_thr = 0.3
if show:
out_file_ort, out_file_pt = None, None
else:
out_file_ort, out_file_pt = 'show-ort.png', 'show-pt.png'
show_img = one_meta['show_img']
model.show_result(
show_img,
pytorch_results,
score_thr=score_thr,
show=True,
win_name='PyTorch',
out_file=out_file_pt)
onnx_model.show_result(
show_img,
onnx_results,
score_thr=score_thr,
show=True,
win_name='ONNXRuntime',
out_file=out_file_ort)
# compare a part of result
if model.with_mask:
compare_pairs = list(zip(onnx_results, pytorch_results))
else:
compare_pairs = [(onnx_results, pytorch_results)]
err_msg = 'The numerical values are different between Pytorch' + \
' and ONNX, but it does not necessarily mean the' + \
' exported ONNX model is problematic.'
# check the numerical value
for onnx_res, pytorch_res in compare_pairs:
for o_res, p_res in zip(onnx_res, pytorch_res):
np.testing.assert_allclose(
o_res, p_res, rtol=1e-03, atol=1e-05, err_msg=err_msg)
print('The numerical values are the same between Pytorch and ONNX')
def parse_normalize_cfg(test_pipeline):
transforms = None
for pipeline in test_pipeline:
if 'transforms' in pipeline:
transforms = pipeline['transforms']
break
assert transforms is not None, 'Failed to find `transforms`'
norm_config_li = [_ for _ in transforms if _['type'] == 'Normalize']
assert len(norm_config_li) == 1, '`norm_config` should only have one'
norm_config = norm_config_li[0]
return norm_config
def parse_args():
parser = argparse.ArgumentParser(
description='Convert MMDetection models to ONNX')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--input-img', type=str, help='Images for input')
parser.add_argument(
'--show',
action='store_true',
help='Show onnx graph and detection outputs')
parser.add_argument('--output-file', type=str, default='tmp.onnx')
parser.add_argument('--opset-version', type=int, default=11)
parser.add_argument(
'--test-img', type=str, default=None, help='Images for test')
parser.add_argument(
'--dataset',
type=str,
default='coco',
help='Dataset name. This argument is deprecated and will be removed \
in future releases.')
parser.add_argument(
'--verify',
action='store_true',
help='verify the onnx model output against pytorch output')
parser.add_argument(
'--simplify',
action='store_true',
help='Whether to simplify onnx model.')
parser.add_argument(
'--shape',
type=int,
nargs='+',
default=[800, 1216],
help='input image size')
parser.add_argument(
'--mean',
type=float,
nargs='+',
default=[123.675, 116.28, 103.53],
help='mean value used for preprocess input data.This argument \
is deprecated and will be removed in future releases.')
parser.add_argument(
'--std',
type=float,
nargs='+',
default=[58.395, 57.12, 57.375],
help='variance value used for preprocess input data. '
'This argument is deprecated and will be removed in future releases.')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='Override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
parser.add_argument(
'--dynamic-export',
action='store_true',
help='Whether to export onnx with dynamic axis.')
parser.add_argument(
'--skip-postprocess',
action='store_true',
help='Whether to export model without post process. Experimental '
'option. We do not guarantee the correctness of the exported '
'model.')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
warnings.warn('Arguments like `--mean`, `--std`, `--dataset` would be \
parsed directly from config file and are deprecated and \
will be removed in future releases.')
assert args.opset_version == 11, 'MMDet only support opset 11 now'
try:
from mmcv.onnx.symbolic import register_extra_symbolics
except ModuleNotFoundError:
raise NotImplementedError('please update mmcv to version>=v1.0.4')
register_extra_symbolics(args.opset_version)
cfg = Config.fromfile(args.config)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
if args.shape is None:
img_scale = cfg.test_pipeline[1]['img_scale']
input_shape = (1, 3, img_scale[1], img_scale[0])
elif len(args.shape) == 1:
input_shape = (1, 3, args.shape[0], args.shape[0])
elif len(args.shape) == 2:
input_shape = (1, 3) + tuple(args.shape)
else:
raise ValueError('invalid input shape')
# build the model and load checkpoint
model = build_model_from_cfg(args.config, args.checkpoint,
args.cfg_options)
if not args.input_img:
args.input_img = osp.join(osp.dirname(__file__), '../../demo/demo.jpg')
normalize_cfg = parse_normalize_cfg(cfg.test_pipeline)
# convert model to onnx file
pytorch2onnx(
model,
args.input_img,
input_shape,
normalize_cfg,
opset_version=args.opset_version,
show=args.show,
output_file=args.output_file,
verify=args.verify,
test_img=args.test_img,
do_simplify=args.simplify,
dynamic_export=args.dynamic_export,
skip_postprocess=args.skip_postprocess)
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = white_background + bright_style + red_text
msg += 'DeprecationWarning: This tool will be deprecated in future. '
msg += blue_text + 'Welcome to use the unified model deployment toolbox '
msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy'
msg += reset_style
warnings.warn(msg)
| 11,729 | 33.098837 | 79 | py |
mmdetection | mmdetection-master/tools/deployment/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
import mmcv
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel
from mmdet.apis import single_gpu_test
from mmdet.datasets import (build_dataloader, build_dataset,
replace_ImageToTensor)
from mmdet.utils import compat_cfg
def parse_args():
parser = argparse.ArgumentParser(
description='MMDet test (and eval) an ONNX model using ONNXRuntime')
parser.add_argument('config', help='test config file path')
parser.add_argument('model', help='Input model file')
parser.add_argument('--out', help='output result file in pickle format')
parser.add_argument(
'--format-only',
action='store_true',
help='Format the output results without perform evaluation. It is'
'useful when you want to format the result to a specific format and '
'submit it to the test server')
parser.add_argument(
'--backend',
required=True,
choices=['onnxruntime', 'tensorrt'],
help='Backend for input model to run. ')
parser.add_argument(
'--eval',
type=str,
nargs='+',
help='evaluation metrics, which depends on the dataset, e.g., "bbox",'
' "segm", "proposal" for COCO, and "mAP", "recall" for PASCAL VOC')
parser.add_argument('--show', action='store_true', help='show results')
parser.add_argument(
'--show-dir', help='directory where painted images will be saved')
parser.add_argument(
'--show-score-thr',
type=float,
default=0.3,
help='score threshold (default: 0.3)')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
parser.add_argument(
'--eval-options',
nargs='+',
action=DictAction,
help='custom options for evaluation, the key-value pair in xxx=yyy '
'format will be kwargs for dataset.evaluate() function')
args = parser.parse_args()
return args
def main():
args = parse_args()
assert args.out or args.eval or args.format_only or args.show \
or args.show_dir, \
('Please specify at least one operation (save/eval/format/show the '
'results / save the results) with the argument "--out", "--eval"'
', "--format-only", "--show" or "--show-dir"')
if args.eval and args.format_only:
raise ValueError('--eval and --format_only cannot be both specified')
if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):
raise ValueError('The output file must be a pkl file.')
cfg = Config.fromfile(args.config)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
cfg = compat_cfg(cfg)
# in case the test dataset is concatenated
samples_per_gpu = 1
if isinstance(cfg.data.test, dict):
cfg.data.test.test_mode = True
samples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1)
if samples_per_gpu > 1:
# Replace 'ImageToTensor' to 'DefaultFormatBundle'
cfg.data.test.pipeline = replace_ImageToTensor(
cfg.data.test.pipeline)
elif isinstance(cfg.data.test, list):
for ds_cfg in cfg.data.test:
ds_cfg.test_mode = True
samples_per_gpu = max(
[ds_cfg.pop('samples_per_gpu', 1) for ds_cfg in cfg.data.test])
if samples_per_gpu > 1:
for ds_cfg in cfg.data.test:
ds_cfg.pipeline = replace_ImageToTensor(ds_cfg.pipeline)
# build the dataloader
dataset = build_dataset(cfg.data.test)
data_loader = build_dataloader(
dataset,
samples_per_gpu=samples_per_gpu,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=False,
shuffle=False)
if args.backend == 'onnxruntime':
from mmdet.core.export.model_wrappers import ONNXRuntimeDetector
model = ONNXRuntimeDetector(
args.model, class_names=dataset.CLASSES, device_id=0)
elif args.backend == 'tensorrt':
from mmdet.core.export.model_wrappers import TensorRTDetector
model = TensorRTDetector(
args.model, class_names=dataset.CLASSES, device_id=0)
model = MMDataParallel(model, device_ids=[0])
outputs = single_gpu_test(model, data_loader, args.show, args.show_dir,
args.show_score_thr)
if args.out:
print(f'\nwriting results to {args.out}')
mmcv.dump(outputs, args.out)
kwargs = {} if args.eval_options is None else args.eval_options
if args.format_only:
dataset.format_results(outputs, **kwargs)
if args.eval:
eval_kwargs = cfg.get('evaluation', {}).copy()
# hard-code way to remove EvalHook args
for key in [
'interval', 'tmpdir', 'start', 'gpu_collect', 'save_best',
'rule'
]:
eval_kwargs.pop(key, None)
eval_kwargs.update(dict(metric=args.eval, **kwargs))
print(dataset.evaluate(outputs, **eval_kwargs))
if __name__ == '__main__':
main()
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = white_background + bright_style + red_text
msg += 'DeprecationWarning: This tool will be deprecated in future. '
msg += blue_text + 'Welcome to use the unified model deployment toolbox '
msg += 'MMDeploy: https://github.com/open-mmlab/mmdeploy'
msg += reset_style
warnings.warn(msg)
| 6,073 | 37.443038 | 78 | py |
mmdetection | mmdetection-master/tools/deployment/test_torchserver.py | from argparse import ArgumentParser
import numpy as np
import requests
from mmdet.apis import inference_detector, init_detector, show_result_pyplot
from mmdet.core import bbox2result
def parse_args():
parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument('model_name', help='The model name in the server')
parser.add_argument(
'--inference-addr',
default='127.0.0.1:8080',
help='Address and port of the inference server')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--score-thr', type=float, default=0.5, help='bbox score threshold')
args = parser.parse_args()
return args
def parse_result(input, model_class):
bbox = []
label = []
score = []
for anchor in input:
bbox.append(anchor['bbox'])
label.append(model_class.index(anchor['class_name']))
score.append([anchor['score']])
bboxes = np.append(bbox, score, axis=1)
labels = np.array(label)
result = bbox2result(bboxes, labels, len(model_class))
return result
def main(args):
# build the model from a config file and a checkpoint file
model = init_detector(args.config, args.checkpoint, device=args.device)
# test a single image
model_result = inference_detector(model, args.img)
for i, anchor_set in enumerate(model_result):
anchor_set = anchor_set[anchor_set[:, 4] >= 0.5]
model_result[i] = anchor_set
# show the results
show_result_pyplot(
model,
args.img,
model_result,
score_thr=args.score_thr,
title='pytorch_result')
url = 'http://' + args.inference_addr + '/predictions/' + args.model_name
with open(args.img, 'rb') as image:
response = requests.post(url, image)
server_result = parse_result(response.json(), model.CLASSES)
show_result_pyplot(
model,
args.img,
server_result,
score_thr=args.score_thr,
title='server_result')
for i in range(len(model.CLASSES)):
assert np.allclose(model_result[i], server_result[i])
if __name__ == '__main__':
args = parse_args()
main(args)
| 2,357 | 30.44 | 77 | py |
mmdetection | mmdetection-master/tools/misc/browse_dataset.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
from collections import Sequence
from pathlib import Path
import mmcv
import numpy as np
from mmcv import Config, DictAction
from mmdet.core.utils import mask2ndarray
from mmdet.core.visualization import imshow_det_bboxes
from mmdet.datasets.builder import build_dataset
from mmdet.utils import replace_cfg_vals, update_data_root
def parse_args():
parser = argparse.ArgumentParser(description='Browse a dataset')
parser.add_argument('config', help='train config file path')
parser.add_argument(
'--skip-type',
type=str,
nargs='+',
default=['DefaultFormatBundle', 'Normalize', 'Collect'],
help='skip some useless pipeline')
parser.add_argument(
'--output-dir',
default=None,
type=str,
help='If there is no display interface, you can save it')
parser.add_argument('--not-show', default=False, action='store_true')
parser.add_argument(
'--show-interval',
type=float,
default=2,
help='the interval of show (s)')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
args = parser.parse_args()
return args
def retrieve_data_cfg(config_path, skip_type, cfg_options):
def skip_pipeline_steps(config):
config['pipeline'] = [
x for x in config.pipeline if x['type'] not in skip_type
]
cfg = Config.fromfile(config_path)
# replace the ${key} with the value of cfg.key
cfg = replace_cfg_vals(cfg)
# update data root according to MMDET_DATASETS
update_data_root(cfg)
if cfg_options is not None:
cfg.merge_from_dict(cfg_options)
train_data_cfg = cfg.data.train
while 'dataset' in train_data_cfg and train_data_cfg[
'type'] != 'MultiImageMixDataset':
train_data_cfg = train_data_cfg['dataset']
if isinstance(train_data_cfg, Sequence):
[skip_pipeline_steps(c) for c in train_data_cfg]
else:
skip_pipeline_steps(train_data_cfg)
return cfg
def main():
args = parse_args()
cfg = retrieve_data_cfg(args.config, args.skip_type, args.cfg_options)
if 'gt_semantic_seg' in cfg.train_pipeline[-1]['keys']:
cfg.data.train.pipeline = [
p for p in cfg.data.train.pipeline if p['type'] != 'SegRescale'
]
dataset = build_dataset(cfg.data.train)
progress_bar = mmcv.ProgressBar(len(dataset))
for item in dataset:
filename = os.path.join(args.output_dir,
Path(item['filename']).name
) if args.output_dir is not None else None
gt_bboxes = item['gt_bboxes']
gt_labels = item['gt_labels']
gt_masks = item.get('gt_masks', None)
if gt_masks is not None:
gt_masks = mask2ndarray(gt_masks)
gt_seg = item.get('gt_semantic_seg', None)
if gt_seg is not None:
pad_value = 255 # the padding value of gt_seg
sem_labels = np.unique(gt_seg)
all_labels = np.concatenate((gt_labels, sem_labels), axis=0)
all_labels, counts = np.unique(all_labels, return_counts=True)
stuff_labels = all_labels[np.logical_and(counts < 2,
all_labels != pad_value)]
stuff_masks = gt_seg[None] == stuff_labels[:, None, None]
gt_labels = np.concatenate((gt_labels, stuff_labels), axis=0)
gt_masks = np.concatenate((gt_masks, stuff_masks.astype(np.uint8)),
axis=0)
# If you need to show the bounding boxes,
# please comment the following line
gt_bboxes = None
imshow_det_bboxes(
item['img'],
gt_bboxes,
gt_labels,
gt_masks,
class_names=dataset.CLASSES,
show=not args.not_show,
wait_time=args.show_interval,
out_file=filename,
bbox_color=dataset.PALETTE,
text_color=(200, 200, 200),
mask_color=dataset.PALETTE)
progress_bar.update()
if __name__ == '__main__':
main()
| 4,664 | 32.804348 | 79 | py |
mmdetection | mmdetection-master/tools/misc/download_dataset.py | import argparse
import tarfile
from itertools import repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from tarfile import TarFile
from zipfile import ZipFile
import torch
from mmcv.utils.path import mkdir_or_exist
def parse_args():
parser = argparse.ArgumentParser(
description='Download datasets for training')
parser.add_argument(
'--dataset-name', type=str, help='dataset name', default='coco2017')
parser.add_argument(
'--save-dir',
type=str,
help='the dir to save dataset',
default='data/coco')
parser.add_argument(
'--unzip',
action='store_true',
help='whether unzip dataset or not, zipped files will be saved')
parser.add_argument(
'--delete',
action='store_true',
help='delete the download zipped files')
parser.add_argument(
'--threads', type=int, help='number of threading', default=4)
args = parser.parse_args()
return args
def download(url, dir, unzip=True, delete=False, threads=1):
def download_one(url, dir):
f = dir / Path(url).name
if Path(url).is_file():
Path(url).rename(f)
elif not f.exists():
print(f'Downloading {url} to {f}')
torch.hub.download_url_to_file(url, f, progress=True)
if unzip and f.suffix in ('.zip', '.tar'):
print(f'Unzipping {f.name}')
if f.suffix == '.zip':
ZipFile(f).extractall(path=dir)
elif f.suffix == '.tar':
TarFile(f).extractall(path=dir)
if delete:
f.unlink()
print(f'Delete {f}')
dir = Path(dir)
if threads > 1:
pool = ThreadPool(threads)
pool.imap(lambda x: download_one(*x), zip(url, repeat(dir)))
pool.close()
pool.join()
else:
for u in [url] if isinstance(url, (str, Path)) else url:
download_one(u, dir)
def download_objects365v2(url, dir, unzip=True, delete=False, threads=1):
def download_single(url, dir):
if 'train' in url:
saving_dir = dir / Path('train_zip')
mkdir_or_exist(saving_dir)
f = saving_dir / Path(url).name
unzip_dir = dir / Path('train')
mkdir_or_exist(unzip_dir)
elif 'val' in url:
saving_dir = dir / Path('val')
mkdir_or_exist(saving_dir)
f = saving_dir / Path(url).name
unzip_dir = dir / Path('val')
mkdir_or_exist(unzip_dir)
else:
raise NotImplementedError
if Path(url).is_file():
Path(url).rename(f)
elif not f.exists():
print(f'Downloading {url} to {f}')
torch.hub.download_url_to_file(url, f, progress=True)
if unzip and str(f).endswith('.tar.gz'):
print(f'Unzipping {f.name}')
tar = tarfile.open(f)
tar.extractall(path=unzip_dir)
if delete:
f.unlink()
print(f'Delete {f}')
# process annotations
full_url = []
for _url in url:
if 'zhiyuan_objv2_train.tar.gz' in _url or \
'zhiyuan_objv2_val.json' in _url:
full_url.append(_url)
elif 'train' in _url:
for i in range(51):
full_url.append(f'{_url}patch{i}.tar.gz')
elif 'val/images/v1' in _url:
for i in range(16):
full_url.append(f'{_url}patch{i}.tar.gz')
elif 'val/images/v2' in _url:
for i in range(16, 44):
full_url.append(f'{_url}patch{i}.tar.gz')
else:
raise NotImplementedError
dir = Path(dir)
if threads > 1:
pool = ThreadPool(threads)
pool.imap(lambda x: download_single(*x), zip(full_url, repeat(dir)))
pool.close()
pool.join()
else:
for u in full_url:
download_single(u, dir)
def main():
args = parse_args()
path = Path(args.save_dir)
if not path.exists():
path.mkdir(parents=True, exist_ok=True)
data2url = dict(
# TODO: Support for downloading Panoptic Segmentation of COCO
coco2017=[
'http://images.cocodataset.org/zips/train2017.zip',
'http://images.cocodataset.org/zips/val2017.zip',
'http://images.cocodataset.org/zips/test2017.zip',
'http://images.cocodataset.org/annotations/' +
'annotations_trainval2017.zip'
],
lvis=[
'https://s3-us-west-2.amazonaws.com/dl.fbaipublicfiles.com/LVIS/lvis_v1_train.json.zip', # noqa
'https://s3-us-west-2.amazonaws.com/dl.fbaipublicfiles.com/LVIS/lvis_v1_train.json.zip', # noqa
],
voc2007=[
'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar', # noqa
'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar', # noqa
'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCdevkit_08-Jun-2007.tar', # noqa
],
# Note: There is no download link for Objects365-V1 right now. If you
# would like to download Objects365-V1, please visit
# http://www.objects365.org/ to concat the author.
objects365v2=[
# training annotations
'https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/zhiyuan_objv2_train.tar.gz', # noqa
# validation annotations
'https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/val/zhiyuan_objv2_val.json', # noqa
# training url root
'https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/', # noqa
# validation url root_1
'https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/val/images/v1/', # noqa
# validation url root_2
'https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/val/images/v2/' # noqa
])
url = data2url.get(args.dataset_name, None)
if url is None:
print('Only support COCO, VOC, LVIS, and Objects365v2 now!')
return
if args.dataset_name == 'objects365v2':
download_objects365v2(
url,
dir=path,
unzip=args.unzip,
delete=args.delete,
threads=args.threads)
else:
download(
url,
dir=path,
unzip=args.unzip,
delete=args.delete,
threads=args.threads)
if __name__ == '__main__':
main()
| 6,727 | 34.225131 | 144 | py |
mmdetection | mmdetection-master/tools/misc/gen_coco_panoptic_test_info.py | import argparse
import os.path as osp
import mmcv
def parse_args():
parser = argparse.ArgumentParser(
description='Generate COCO test image information '
'for COCO panoptic segmentation.')
parser.add_argument('data_root', help='Path to COCO annotation directory.')
args = parser.parse_args()
return args
def main():
args = parse_args()
data_root = args.data_root
val_info = mmcv.load(osp.join(data_root, 'panoptic_val2017.json'))
test_old_info = mmcv.load(
osp.join(data_root, 'image_info_test-dev2017.json'))
# replace categories from image_info_test-dev2017.json
# with categories from panoptic_val2017.json which
# has attribute `isthing`.
test_info = test_old_info
test_info.update({'categories': val_info['categories']})
mmcv.dump(test_info,
osp.join(data_root, 'panoptic_image_info_test-dev2017.json'))
if __name__ == '__main__':
main()
| 950 | 26.171429 | 79 | py |
mmdetection | mmdetection-master/tools/misc/get_image_metas.py | # Copyright (c) OpenMMLab. All rights reserved.
"""Get test image metas on a specific dataset.
Here is an example to run this script.
Example:
python tools/misc/get_image_metas.py ${CONFIG} \
--out ${OUTPUT FILE NAME}
"""
import argparse
import csv
import os.path as osp
from multiprocessing import Pool
import mmcv
from mmcv import Config
def parse_args():
parser = argparse.ArgumentParser(description='Collect image metas')
parser.add_argument('config', help='Config file path')
parser.add_argument(
'--out',
default='validation-image-metas.pkl',
help='The output image metas file name. The save dir is in the '
'same directory as `dataset.ann_file` path')
parser.add_argument(
'--nproc',
default=4,
type=int,
help='Processes used for get image metas')
args = parser.parse_args()
return args
def get_metas_from_csv_style_ann_file(ann_file):
data_infos = []
cp_filename = None
with open(ann_file, 'r') as f:
reader = csv.reader(f)
for i, line in enumerate(reader):
if i == 0:
continue
img_id = line[0]
filename = f'{img_id}.jpg'
if filename != cp_filename:
data_infos.append(dict(filename=filename))
cp_filename = filename
return data_infos
def get_metas_from_txt_style_ann_file(ann_file):
with open(ann_file) as f:
lines = f.readlines()
i = 0
data_infos = []
while i < len(lines):
filename = lines[i].rstrip()
data_infos.append(dict(filename=filename))
skip_lines = int(lines[i + 2]) + 3
i += skip_lines
return data_infos
def get_image_metas(data_info, img_prefix):
file_client = mmcv.FileClient(backend='disk')
filename = data_info.get('filename', None)
if filename is not None:
if img_prefix is not None:
filename = osp.join(img_prefix, filename)
img_bytes = file_client.get(filename)
img = mmcv.imfrombytes(img_bytes, flag='color')
meta = dict(filename=filename, ori_shape=img.shape)
else:
raise NotImplementedError('Missing `filename` in data_info')
return meta
def main():
args = parse_args()
assert args.out.endswith('pkl'), 'The output file name must be pkl suffix'
# load config files
cfg = Config.fromfile(args.config)
ann_file = cfg.data.test.ann_file
img_prefix = cfg.data.test.img_prefix
print(f'{"-" * 5} Start Processing {"-" * 5}')
if ann_file.endswith('csv'):
data_infos = get_metas_from_csv_style_ann_file(ann_file)
elif ann_file.endswith('txt'):
data_infos = get_metas_from_txt_style_ann_file(ann_file)
else:
shuffix = ann_file.split('.')[-1]
raise NotImplementedError('File name must be csv or txt suffix but '
f'get {shuffix}')
print(f'Successfully load annotation file from {ann_file}')
print(f'Processing {len(data_infos)} images...')
pool = Pool(args.nproc)
# get image metas with multiple processes
image_metas = pool.starmap(
get_image_metas,
zip(data_infos, [img_prefix for _ in range(len(data_infos))]),
)
pool.close()
# save image metas
root_path = cfg.data.test.ann_file.rsplit('/', 1)[0]
save_path = osp.join(root_path, args.out)
mmcv.dump(image_metas, save_path)
print(f'Image meta file save to: {save_path}')
if __name__ == '__main__':
main()
| 3,526 | 29.145299 | 78 | py |
mmdetection | mmdetection-master/tools/misc/print_config.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
from mmcv import Config, DictAction
from mmdet.utils import replace_cfg_vals, update_data_root
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument(
'--options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file (deprecate), '
'change to --cfg-options instead.')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
args = parser.parse_args()
if args.options and args.cfg_options:
raise ValueError(
'--options and --cfg-options cannot be both '
'specified, --options is deprecated in favor of --cfg-options')
if args.options:
warnings.warn('--options is deprecated in favor of --cfg-options')
args.cfg_options = args.options
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
# replace the ${key} with the value of cfg.key
cfg = replace_cfg_vals(cfg)
# update data root according to MMDET_DATASETS
update_data_root(cfg)
if args.cfg_options is not None:
cfg.merge_from_dict(args.cfg_options)
print(f'Config:\n{cfg.pretty_text}')
if __name__ == '__main__':
main()
| 1,920 | 30.491803 | 78 | py |
mmdetection | mmdetection-master/tools/misc/split_coco.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import mmcv
import numpy as np
prog_description = '''K-Fold coco split.
To split coco data for semi-supervised object detection:
python tools/misc/split_coco.py
'''
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-root',
type=str,
help='The data root of coco dataset.',
default='./data/coco/')
parser.add_argument(
'--out-dir',
type=str,
help='The output directory of coco semi-supervised annotations.',
default='./data/coco_semi_annos/')
parser.add_argument(
'--labeled-percent',
type=float,
nargs='+',
help='The percentage of labeled data in the training set.',
default=[1, 2, 5, 10])
parser.add_argument(
'--fold',
type=int,
help='K-fold cross validation for semi-supervised object detection.',
default=5)
args = parser.parse_args()
return args
def split_coco(data_root, out_dir, percent, fold):
"""Split COCO data for Semi-supervised object detection.
Args:
data_root (str): The data root of coco dataset.
out_dir (str): The output directory of coco semi-supervised
annotations.
percent (float): The percentage of labeled data in the training set.
fold (int): The fold of dataset and set as random seed for data split.
"""
def save_anns(name, images, annotations):
sub_anns = dict()
sub_anns['images'] = images
sub_anns['annotations'] = annotations
sub_anns['licenses'] = anns['licenses']
sub_anns['categories'] = anns['categories']
sub_anns['info'] = anns['info']
mmcv.mkdir_or_exist(out_dir)
mmcv.dump(sub_anns, f'{out_dir}/{name}.json')
# set random seed with the fold
np.random.seed(fold)
ann_file = osp.join(data_root, 'annotations/instances_train2017.json')
anns = mmcv.load(ann_file)
image_list = anns['images']
labeled_total = int(percent / 100. * len(image_list))
labeled_inds = set(
np.random.choice(range(len(image_list)), size=labeled_total))
labeled_ids, labeled_images, unlabeled_images = [], [], []
for i in range(len(image_list)):
if i in labeled_inds:
labeled_images.append(image_list[i])
labeled_ids.append(image_list[i]['id'])
else:
unlabeled_images.append(image_list[i])
# get all annotations of labeled images
labeled_ids = set(labeled_ids)
labeled_annotations, unlabeled_annotations = [], []
for ann in anns['annotations']:
if ann['image_id'] in labeled_ids:
labeled_annotations.append(ann)
else:
unlabeled_annotations.append(ann)
# save labeled and unlabeled
labeled_name = f'instances_train2017.{fold}@{percent}'
unlabeled_name = f'instances_train2017.{fold}@{percent}-unlabeled'
save_anns(labeled_name, labeled_images, labeled_annotations)
save_anns(unlabeled_name, unlabeled_images, unlabeled_annotations)
def multi_wrapper(args):
return split_coco(*args)
if __name__ == '__main__':
args = parse_args()
arguments_list = [(args.data_root, args.out_dir, p, f)
for f in range(1, args.fold + 1)
for p in args.labeled_percent]
mmcv.track_parallel_progress(multi_wrapper, arguments_list, args.fold)
| 3,487 | 30.709091 | 78 | py |
mmdetection | mmdetection-master/tools/model_converters/detectron2pytorch.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
import mmcv
import torch
arch_settings = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3)}
def convert_bn(blobs, state_dict, caffe_name, torch_name, converted_names):
# detectron replace bn with affine channel layer
state_dict[torch_name + '.bias'] = torch.from_numpy(blobs[caffe_name +
'_b'])
state_dict[torch_name + '.weight'] = torch.from_numpy(blobs[caffe_name +
'_s'])
bn_size = state_dict[torch_name + '.weight'].size()
state_dict[torch_name + '.running_mean'] = torch.zeros(bn_size)
state_dict[torch_name + '.running_var'] = torch.ones(bn_size)
converted_names.add(caffe_name + '_b')
converted_names.add(caffe_name + '_s')
def convert_conv_fc(blobs, state_dict, caffe_name, torch_name,
converted_names):
state_dict[torch_name + '.weight'] = torch.from_numpy(blobs[caffe_name +
'_w'])
converted_names.add(caffe_name + '_w')
if caffe_name + '_b' in blobs:
state_dict[torch_name + '.bias'] = torch.from_numpy(blobs[caffe_name +
'_b'])
converted_names.add(caffe_name + '_b')
def convert(src, dst, depth):
"""Convert keys in detectron pretrained ResNet models to pytorch style."""
# load arch_settings
if depth not in arch_settings:
raise ValueError('Only support ResNet-50 and ResNet-101 currently')
block_nums = arch_settings[depth]
# load caffe model
caffe_model = mmcv.load(src, encoding='latin1')
blobs = caffe_model['blobs'] if 'blobs' in caffe_model else caffe_model
# convert to pytorch style
state_dict = OrderedDict()
converted_names = set()
convert_conv_fc(blobs, state_dict, 'conv1', 'conv1', converted_names)
convert_bn(blobs, state_dict, 'res_conv1_bn', 'bn1', converted_names)
for i in range(1, len(block_nums) + 1):
for j in range(block_nums[i - 1]):
if j == 0:
convert_conv_fc(blobs, state_dict, f'res{i + 1}_{j}_branch1',
f'layer{i}.{j}.downsample.0', converted_names)
convert_bn(blobs, state_dict, f'res{i + 1}_{j}_branch1_bn',
f'layer{i}.{j}.downsample.1', converted_names)
for k, letter in enumerate(['a', 'b', 'c']):
convert_conv_fc(blobs, state_dict,
f'res{i + 1}_{j}_branch2{letter}',
f'layer{i}.{j}.conv{k+1}', converted_names)
convert_bn(blobs, state_dict,
f'res{i + 1}_{j}_branch2{letter}_bn',
f'layer{i}.{j}.bn{k + 1}', converted_names)
# check if all layers are converted
for key in blobs:
if key not in converted_names:
print(f'Not Convert: {key}')
# save checkpoint
checkpoint = dict()
checkpoint['state_dict'] = state_dict
torch.save(checkpoint, dst)
def main():
parser = argparse.ArgumentParser(description='Convert model keys')
parser.add_argument('src', help='src detectron model path')
parser.add_argument('dst', help='save path')
parser.add_argument('depth', type=int, help='ResNet model depth')
args = parser.parse_args()
convert(args.src, args.dst, args.depth)
if __name__ == '__main__':
main()
| 3,578 | 41.607143 | 78 | py |
mmdetection | mmdetection-master/tools/model_converters/publish_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import subprocess
import torch
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = parser.parse_args()
return args
def process_checkpoint(in_file, out_file):
checkpoint = torch.load(in_file, map_location='cpu')
# remove optimizer for smaller file size
if 'optimizer' in checkpoint:
del checkpoint['optimizer']
# if it is necessary to remove some sensitive data in checkpoint['meta'],
# add the code here.
if torch.__version__ >= '1.6':
torch.save(checkpoint, out_file, _use_new_zipfile_serialization=False)
else:
torch.save(checkpoint, out_file)
sha = subprocess.check_output(['sha256sum', out_file]).decode()
if out_file.endswith('.pth'):
out_file_name = out_file[:-4]
else:
out_file_name = out_file
final_file = out_file_name + f'-{sha[:8]}.pth'
subprocess.Popen(['mv', out_file, final_file])
def main():
args = parse_args()
process_checkpoint(args.in_file, args.out_file)
if __name__ == '__main__':
main()
| 1,301 | 28.590909 | 78 | py |
mmdetection | mmdetection-master/tools/model_converters/regnet2mmdet.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
import torch
def convert_stem(model_key, model_weight, state_dict, converted_names):
new_key = model_key.replace('stem.conv', 'conv1')
new_key = new_key.replace('stem.bn', 'bn1')
state_dict[new_key] = model_weight
converted_names.add(model_key)
print(f'Convert {model_key} to {new_key}')
def convert_head(model_key, model_weight, state_dict, converted_names):
new_key = model_key.replace('head.fc', 'fc')
state_dict[new_key] = model_weight
converted_names.add(model_key)
print(f'Convert {model_key} to {new_key}')
def convert_reslayer(model_key, model_weight, state_dict, converted_names):
split_keys = model_key.split('.')
layer, block, module = split_keys[:3]
block_id = int(block[1:])
layer_name = f'layer{int(layer[1:])}'
block_name = f'{block_id - 1}'
if block_id == 1 and module == 'bn':
new_key = f'{layer_name}.{block_name}.downsample.1.{split_keys[-1]}'
elif block_id == 1 and module == 'proj':
new_key = f'{layer_name}.{block_name}.downsample.0.{split_keys[-1]}'
elif module == 'f':
if split_keys[3] == 'a_bn':
module_name = 'bn1'
elif split_keys[3] == 'b_bn':
module_name = 'bn2'
elif split_keys[3] == 'c_bn':
module_name = 'bn3'
elif split_keys[3] == 'a':
module_name = 'conv1'
elif split_keys[3] == 'b':
module_name = 'conv2'
elif split_keys[3] == 'c':
module_name = 'conv3'
new_key = f'{layer_name}.{block_name}.{module_name}.{split_keys[-1]}'
else:
raise ValueError(f'Unsupported conversion of key {model_key}')
print(f'Convert {model_key} to {new_key}')
state_dict[new_key] = model_weight
converted_names.add(model_key)
def convert(src, dst):
"""Convert keys in pycls pretrained RegNet models to mmdet style."""
# load caffe model
regnet_model = torch.load(src)
blobs = regnet_model['model_state']
# convert to pytorch style
state_dict = OrderedDict()
converted_names = set()
for key, weight in blobs.items():
if 'stem' in key:
convert_stem(key, weight, state_dict, converted_names)
elif 'head' in key:
convert_head(key, weight, state_dict, converted_names)
elif key.startswith('s'):
convert_reslayer(key, weight, state_dict, converted_names)
# check if all layers are converted
for key in blobs:
if key not in converted_names:
print(f'not converted: {key}')
# save checkpoint
checkpoint = dict()
checkpoint['state_dict'] = state_dict
torch.save(checkpoint, dst)
def main():
parser = argparse.ArgumentParser(description='Convert model keys')
parser.add_argument('src', help='src detectron model path')
parser.add_argument('dst', help='save path')
args = parser.parse_args()
convert(args.src, args.dst)
if __name__ == '__main__':
main()
| 3,063 | 32.67033 | 77 | py |
mmdetection | mmdetection-master/tools/model_converters/selfsup2mmdet.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
import torch
def moco_convert(src, dst):
"""Convert keys in pycls pretrained moco models to mmdet style."""
# load caffe model
moco_model = torch.load(src)
blobs = moco_model['state_dict']
# convert to pytorch style
state_dict = OrderedDict()
for k, v in blobs.items():
if not k.startswith('module.encoder_q.'):
continue
old_k = k
k = k.replace('module.encoder_q.', '')
state_dict[k] = v
print(old_k, '->', k)
# save checkpoint
checkpoint = dict()
checkpoint['state_dict'] = state_dict
torch.save(checkpoint, dst)
def main():
parser = argparse.ArgumentParser(description='Convert model keys')
parser.add_argument('src', help='src detectron model path')
parser.add_argument('dst', help='save path')
parser.add_argument(
'--selfsup', type=str, choices=['moco', 'swav'], help='save path')
args = parser.parse_args()
if args.selfsup == 'moco':
moco_convert(args.src, args.dst)
elif args.selfsup == 'swav':
print('SWAV does not need to convert the keys')
if __name__ == '__main__':
main()
| 1,243 | 27.930233 | 74 | py |
mmdetection | mmdetection-master/tools/model_converters/upgrade_model_version.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import re
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def is_head(key):
valid_head_list = [
'bbox_head', 'mask_head', 'semantic_head', 'grid_head', 'mask_iou_head'
]
return any(key.startswith(h) for h in valid_head_list)
def parse_config(config_strings):
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
f.write(config_strings)
config = Config.fromfile(config_path)
is_two_stage = True
is_ssd = False
is_retina = False
reg_cls_agnostic = False
if 'rpn_head' not in config.model:
is_two_stage = False
# check whether it is SSD
if config.model.bbox_head.type == 'SSDHead':
is_ssd = True
elif config.model.bbox_head.type == 'RetinaHead':
is_retina = True
elif isinstance(config.model['bbox_head'], list):
reg_cls_agnostic = True
elif 'reg_class_agnostic' in config.model.bbox_head:
reg_cls_agnostic = config.model.bbox_head \
.reg_class_agnostic
temp_file.close()
return is_two_stage, is_ssd, is_retina, reg_cls_agnostic
def reorder_cls_channel(val, num_classes=81):
# bias
if val.dim() == 1:
new_val = torch.cat((val[1:], val[:1]), dim=0)
# weight
else:
out_channels, in_channels = val.shape[:2]
# conv_cls for softmax output
if out_channels != num_classes and out_channels % num_classes == 0:
new_val = val.reshape(-1, num_classes, in_channels, *val.shape[2:])
new_val = torch.cat((new_val[:, 1:], new_val[:, :1]), dim=1)
new_val = new_val.reshape(val.size())
# fc_cls
elif out_channels == num_classes:
new_val = torch.cat((val[1:], val[:1]), dim=0)
# agnostic | retina_cls | rpn_cls
else:
new_val = val
return new_val
def truncate_cls_channel(val, num_classes=81):
# bias
if val.dim() == 1:
if val.size(0) % num_classes == 0:
new_val = val[:num_classes - 1]
else:
new_val = val
# weight
else:
out_channels, in_channels = val.shape[:2]
# conv_logits
if out_channels % num_classes == 0:
new_val = val.reshape(num_classes, in_channels, *val.shape[2:])[1:]
new_val = new_val.reshape(-1, *val.shape[1:])
# agnostic
else:
new_val = val
return new_val
def truncate_reg_channel(val, num_classes=81):
# bias
if val.dim() == 1:
# fc_reg | rpn_reg
if val.size(0) % num_classes == 0:
new_val = val.reshape(num_classes, -1)[:num_classes - 1]
new_val = new_val.reshape(-1)
# agnostic
else:
new_val = val
# weight
else:
out_channels, in_channels = val.shape[:2]
# fc_reg | rpn_reg
if out_channels % num_classes == 0:
new_val = val.reshape(num_classes, -1, in_channels,
*val.shape[2:])[1:]
new_val = new_val.reshape(-1, *val.shape[1:])
# agnostic
else:
new_val = val
return new_val
def convert(in_file, out_file, num_classes):
"""Convert keys in checkpoints.
There can be some breaking changes during the development of mmdetection,
and this tool is used for upgrading checkpoints trained with old versions
to the latest one.
"""
checkpoint = torch.load(in_file)
in_state_dict = checkpoint.pop('state_dict')
out_state_dict = OrderedDict()
meta_info = checkpoint['meta']
is_two_stage, is_ssd, is_retina, reg_cls_agnostic = parse_config(
'#' + meta_info['config'])
if meta_info['mmdet_version'] <= '0.5.3' and is_retina:
upgrade_retina = True
else:
upgrade_retina = False
# MMDetection v2.5.0 unifies the class order in RPN
# if the model is trained in version<v2.5.0
# The RPN model should be upgraded to be used in version>=2.5.0
if meta_info['mmdet_version'] < '2.5.0':
upgrade_rpn = True
else:
upgrade_rpn = False
for key, val in in_state_dict.items():
new_key = key
new_val = val
if is_two_stage and is_head(key):
new_key = 'roi_head.{}'.format(key)
# classification
if upgrade_rpn:
m = re.search(
r'(conv_cls|retina_cls|rpn_cls|fc_cls|fcos_cls|'
r'fovea_cls).(weight|bias)', new_key)
else:
m = re.search(
r'(conv_cls|retina_cls|fc_cls|fcos_cls|'
r'fovea_cls).(weight|bias)', new_key)
if m is not None:
print(f'reorder cls channels of {new_key}')
new_val = reorder_cls_channel(val, num_classes)
# regression
if upgrade_rpn:
m = re.search(r'(fc_reg).(weight|bias)', new_key)
else:
m = re.search(r'(fc_reg|rpn_reg).(weight|bias)', new_key)
if m is not None and not reg_cls_agnostic:
print(f'truncate regression channels of {new_key}')
new_val = truncate_reg_channel(val, num_classes)
# mask head
m = re.search(r'(conv_logits).(weight|bias)', new_key)
if m is not None:
print(f'truncate mask prediction channels of {new_key}')
new_val = truncate_cls_channel(val, num_classes)
m = re.search(r'(cls_convs|reg_convs).\d.(weight|bias)', key)
# Legacy issues in RetinaNet since V1.x
# Use ConvModule instead of nn.Conv2d in RetinaNet
# cls_convs.0.weight -> cls_convs.0.conv.weight
if m is not None and upgrade_retina:
param = m.groups()[1]
new_key = key.replace(param, f'conv.{param}')
out_state_dict[new_key] = val
print(f'rename the name of {key} to {new_key}')
continue
m = re.search(r'(cls_convs).\d.(weight|bias)', key)
if m is not None and is_ssd:
print(f'reorder cls channels of {new_key}')
new_val = reorder_cls_channel(val, num_classes)
out_state_dict[new_key] = new_val
checkpoint['state_dict'] = out_state_dict
torch.save(checkpoint, out_file)
def main():
parser = argparse.ArgumentParser(description='Upgrade model version')
parser.add_argument('in_file', help='input checkpoint file')
parser.add_argument('out_file', help='output checkpoint file')
parser.add_argument(
'--num-classes',
type=int,
default=81,
help='number of classes of the original model')
args = parser.parse_args()
convert(args.in_file, args.out_file, args.num_classes)
if __name__ == '__main__':
main()
| 6,848 | 31.459716 | 79 | py |
mmdetection | mmdetection-master/tools/model_converters/upgrade_ssd_version.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def parse_config(config_strings):
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
f.write(config_strings)
config = Config.fromfile(config_path)
# check whether it is SSD
if config.model.bbox_head.type != 'SSDHead':
raise AssertionError('This is not a SSD model.')
def convert(in_file, out_file):
checkpoint = torch.load(in_file)
in_state_dict = checkpoint.pop('state_dict')
out_state_dict = OrderedDict()
meta_info = checkpoint['meta']
parse_config('#' + meta_info['config'])
for key, value in in_state_dict.items():
if 'extra' in key:
layer_idx = int(key.split('.')[2])
new_key = 'neck.extra_layers.{}.{}.conv.'.format(
layer_idx // 2, layer_idx % 2) + key.split('.')[-1]
elif 'l2_norm' in key:
new_key = 'neck.l2_norm.weight'
elif 'bbox_head' in key:
new_key = key[:21] + '.0' + key[21:]
else:
new_key = key
out_state_dict[new_key] = value
checkpoint['state_dict'] = out_state_dict
if torch.__version__ >= '1.6':
torch.save(checkpoint, out_file, _use_new_zipfile_serialization=False)
else:
torch.save(checkpoint, out_file)
def main():
parser = argparse.ArgumentParser(description='Upgrade SSD version')
parser.add_argument('in_file', help='input checkpoint file')
parser.add_argument('out_file', help='output checkpoint file')
args = parser.parse_args()
convert(args.in_file, args.out_file)
if __name__ == '__main__':
main()
| 1,789 | 29.338983 | 78 | py |
null | AICP-main/README.md | # AICP
The datasets and code for the experiments of the following paper:
''Augmented Informative Cooperative Perception''
``/sort/objects.json`` contains the detected object data.
``/sort/weightedFitnessSort.ipynb`` is the easy-to-use jupyter notebook containing the weighted fitness sorting algorithm code.
``/veins/examples/veins/antenna.xml`` contains the front-rear antenna configuration.
``/veins/src/veins/modules/`` contains the simulation code for CMR.
| 467 | 35 | 127 | md |
null | AICP-main/veins/src/veins/modules/analogueModel/BreakpointPathlossModel.cc | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/BreakpointPathlossModel.h"
#include "veins/base/messages/AirFrame_m.h"
using namespace veins;
using veins::AirFrame;
void BreakpointPathlossModel::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
/** Calculate the distance factor */
double distance = useTorus ? receiverPos.sqrTorusDist(senderPos, playgroundSize) : receiverPos.sqrdist(senderPos);
distance = sqrt(distance);
EV_TRACE << "distance is: " << distance << endl;
if (distance <= 1.0) {
// attenuation is negligible
return;
}
double attenuation = 1;
// PL(d) = PL0 + 10 alpha log10 (d/d0)
// 10 ^ { PL(d)/10 } = 10 ^{PL0 + 10 alpha log10 (d/d0)}/10
// 10 ^ { PL(d)/10 } = 10 ^ PL0/10 * 10 ^ { 10 log10 (d/d0)^alpha }/10
// 10 ^ { PL(d)/10 } = 10 ^ PL0/10 * 10 ^ { log10 (d/d0)^alpha }
// 10 ^ { PL(d)/10 } = 10 ^ PL0/10 * (d/d0)^alpha
if (distance < breakpointDistance) {
attenuation = attenuation * PL01_real;
attenuation = attenuation * pow(distance, alpha1);
}
else {
attenuation = attenuation * PL02_real;
attenuation = attenuation * pow(distance / breakpointDistance, alpha2);
}
attenuation = 1 / attenuation;
EV_TRACE << "attenuation is: " << attenuation << endl;
pathlosses.record(10 * log10(attenuation)); // in dB
*signal *= attenuation;
}
| 2,571 | 36.823529 | 118 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/BreakpointPathlossModel.h | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <cstdlib>
#include "veins/veins.h"
#include "veins/base/phyLayer/AnalogueModel.h"
using veins::AirFrame;
namespace veins {
/**
* @brief Basic implementation of a BreakpointPathlossModel.
* This class can be used to implement the ieee802154 path loss model.
*
* @ingroup analogueModels
*/
class VEINS_API BreakpointPathlossModel : public AnalogueModel {
protected:
// /** @brief Model to use for distances below breakpoint distance */
// SimplePathlossModel closeRangeModel;
// /** @brief Model to use for distances larger than the breakpoint distance */
// SimplePathlossModel farRangeModel;
/** @brief initial path loss in dB */
double PL01, PL02;
/** @brief initial path loss */
double PL01_real, PL02_real;
/** @brief pathloss exponents */
double alpha1, alpha2;
/** @brief Breakpoint distance squared. */
double breakpointDistance;
/** @brief Information needed about the playground */
const bool useTorus;
/** @brief The size of the playground.*/
const Coord& playgroundSize;
/** logs computed pathlosses. */
cOutVector pathlosses;
public:
/**
* @brief Initializes the analogue model. playgroundSize
* need to be valid as long as this instance exists.
*/
BreakpointPathlossModel(cComponent* owner, double L01, double L02, double alpha1, double alpha2, double breakpointDistance, bool useTorus, const Coord& playgroundSize)
: AnalogueModel(owner)
, PL01(L01)
, PL02(L02)
, alpha1(alpha1)
, alpha2(alpha2)
, breakpointDistance(breakpointDistance)
, useTorus(useTorus)
, playgroundSize(playgroundSize)
{
PL01_real = pow(10, PL01 / 10);
PL02_real = pow(10, PL02 / 10);
pathlosses.setName("pathlosses");
}
/**
* @brief Filters a specified AirFrame's Signal by adding an attenuation
* over time to the Signal.
*/
void filterSignal(Signal*) override;
virtual bool isActiveAtDestination()
{
return true;
}
virtual bool isActiveAtOrigin()
{
return false;
}
};
} // namespace veins
| 3,259 | 29.185185 | 171 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/NakagamiFading.cc | //
// Copyright (C) 2015 David Eckhoff <[email protected]>
// Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/NakagamiFading.h"
using namespace veins;
/**
* Simple Nakagami-m fading (based on a constant factor across all time and frequencies).
*/
void NakagamiFading::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
const double M_CLOSE = 1.5;
const double M_FAR = 0.75;
const double DIS_THRESHOLD = 80;
EV_TRACE << "Add NakagamiFading ..." << endl;
// get average TX power
// FIXME: really use average power (instead of max)
EV_TRACE << "Finding max TX power ..." << endl;
double sendPower_mW = signal->getMax();
EV_TRACE << "TX power is " << FWMath::mW2dBm(sendPower_mW) << " dBm" << endl;
// get m value
double m = this->m;
{
const Coord senderPos2D(senderPos.x, senderPos.y);
const Coord receiverPos2D(receiverPos.x, receiverPos.y);
double d = senderPos2D.distance(receiverPos2D);
if (!constM) {
m = (d < DIS_THRESHOLD) ? M_CLOSE : M_FAR;
}
}
// calculate average RX power
double recvPower_mW = (RNGCONTEXT gamma_d(m, sendPower_mW / 1000 / m)) * 1000.0;
if (recvPower_mW > sendPower_mW) {
recvPower_mW = sendPower_mW;
}
EV_TRACE << "RX power is " << FWMath::mW2dBm(recvPower_mW) << " dBm" << endl;
// infer average attenuation
double factor = recvPower_mW / sendPower_mW;
EV_TRACE << "factor is: " << factor << " (i.e. " << FWMath::mW2dBm(factor) << " dB)" << endl;
*signal *= factor;
}
| 2,554 | 34.486111 | 97 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/NakagamiFading.h | //
// Copyright (C) 2015 David Eckhoff <[email protected]>
// Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/base/phyLayer/AnalogueModel.h"
#include "veins/base/modules/BaseWorldUtility.h"
#include "veins/base/messages/AirFrame_m.h"
namespace veins {
/**
* @brief
* A simple model to account for fast fading using the Nakagami Distribution.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* An in-depth description of the model is available at:
* Todo: add paper
*
* @author David Eckhoff, Christoph Sommer
*
* @ingroup analogueModels
*/
class VEINS_API NakagamiFading : public AnalogueModel {
public:
NakagamiFading(cComponent* owner, bool constM, double m)
: AnalogueModel(owner)
, constM(constM)
, m(m)
{
}
~NakagamiFading() override
{
}
void filterSignal(Signal* signal) override;
protected:
/** @brief Whether to use a constant m or a m based on distance */
bool constM;
/** @brief The value of the coefficient m */
double m;
};
} // namespace veins
| 1,992 | 27.471429 | 113 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/PERModel.cc | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/PERModel.h"
#include "veins/base/messages/AirFrame_m.h"
using namespace veins;
using veins::AirFrame;
void PERModel::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
double attenuationFactor = 1; // no attenuation
if (packetErrorRate > 0 && RNGCONTEXT uniform(0, 1) < packetErrorRate) {
attenuationFactor = 0; // absorb all energy so that the receveir cannot receive anything
}
*signal *= attenuationFactor;
}
| 1,665 | 36.863636 | 101 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/PERModel.h | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
#include "veins/base/phyLayer/AnalogueModel.h"
using veins::AirFrame;
namespace veins {
/**
* @brief This class applies a parameterized packet error rate
* to incoming packets. This allows the user to easily
* study the robustness of its system to packet loss.
*
* @ingroup analogueModels
*
* @author Jérôme Rousselot <[email protected]>
*/
class VEINS_API PERModel : public AnalogueModel {
protected:
double packetErrorRate;
public:
/** @brief The PERModel constructor takes as argument the packet error rate to apply (must be between 0 and 1). */
PERModel(cComponent* owner, double per)
: AnalogueModel(owner)
, packetErrorRate(per)
{
ASSERT(per <= 1 && per >= 0);
}
void filterSignal(Signal*) override;
};
} // namespace veins
| 1,911 | 30.344262 | 118 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/SimpleObstacleShadowing.cc | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/SimpleObstacleShadowing.h"
using namespace veins;
using veins::AirFrame;
SimpleObstacleShadowing::SimpleObstacleShadowing(cComponent* owner, ObstacleControl& obstacleControl, bool useTorus, const Coord& playgroundSize)
: AnalogueModel(owner)
, obstacleControl(obstacleControl)
, useTorus(useTorus)
, playgroundSize(playgroundSize)
{
if (useTorus) throw cRuntimeError("SimpleObstacleShadowing does not work on torus-shaped playgrounds");
}
void SimpleObstacleShadowing::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
double factor = obstacleControl.calculateAttenuation(senderPos, receiverPos);
EV_TRACE << "value is: " << factor << endl;
*signal *= factor;
}
| 1,759 | 34.918367 | 145 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/SimpleObstacleShadowing.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <cstdlib>
#include "veins/base/phyLayer/AnalogueModel.h"
#include "veins/base/modules/BaseWorldUtility.h"
#include "veins/modules/obstacle/ObstacleControl.h"
#include "veins/base/utils/Move.h"
#include "veins/base/messages/AirFrame_m.h"
using veins::AirFrame;
using veins::ObstacleControl;
namespace veins {
class Signal;
/**
* @brief Basic implementation of a SimpleObstacleShadowing
*
* @ingroup analogueModels
*/
class VEINS_API SimpleObstacleShadowing : public AnalogueModel {
protected:
/** @brief reference to global ObstacleControl instance */
ObstacleControl& obstacleControl;
/** @brief Information needed about the playground */
const bool useTorus;
/** @brief The size of the playground.*/
const Coord& playgroundSize;
public:
/**
* @brief Initializes the analogue model. myMove and playgroundSize
* need to be valid as long as this instance exists.
*
* The constructor needs some specific knowledge in order to create
* its mapping properly:
*
* @param owner pointer to the cComponent that owns this AnalogueModel
* @param obstacleControl the parent module
* @param useTorus information about the playground the host is moving in
* @param playgroundSize information about the playground the host is moving in
*/
SimpleObstacleShadowing(cComponent* owner, ObstacleControl& obstacleControl, bool useTorus, const Coord& playgroundSize);
/**
* @brief Filters a specified Signal by adding an attenuation
* over time to the Signal.
*/
void filterSignal(Signal* signal) override;
bool neverIncreasesPower() override
{
return true;
}
};
} // namespace veins
| 2,635 | 30.380952 | 125 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/SimplePathlossModel.cc | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/SimplePathlossModel.h"
#include "veins/base/messages/AirFrame_m.h"
using namespace veins;
using veins::AirFrame;
void SimplePathlossModel::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
/** Calculate the distance factor */
double sqrDistance = useTorus ? receiverPos.sqrTorusDist(senderPos, playgroundSize) : receiverPos.sqrdist(senderPos);
EV_TRACE << "sqrdistance is: " << sqrDistance << endl;
if (sqrDistance <= 1.0) {
// attenuation is negligible
return;
}
// the part of the attenuation only depending on the distance
double distFactor = pow(sqrDistance, -pathLossAlphaHalf) / (16.0 * M_PI * M_PI);
EV_TRACE << "distance factor is: " << distFactor << endl;
Signal attenuation(signal->getSpectrum());
for (uint16_t i = 0; i < signal->getNumValues(); i++) {
double wavelength = BaseWorldUtility::speedOfLight() / signal->getSpectrum().freqAt(i);
attenuation.at(i) = (wavelength * wavelength) * distFactor;
}
*signal *= attenuation;
}
| 2,254 | 37.220339 | 121 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/SimplePathlossModel.h | //
// Copyright (C) 2007 Technische Universitaet Berlin (TUB), Germany, Telecommunication Networks Group
// Copyright (C) 2007 Technische Universiteit Delft (TUD), Netherlands
// Copyright (C) 2007 Universitaet Paderborn (UPB), Germany
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <cstdlib>
#include "veins/veins.h"
#include "veins/base/phyLayer/AnalogueModel.h"
#include "veins/base/modules/BaseWorldUtility.h"
namespace veins {
using veins::AirFrame;
class SimplePathlossModel;
/**
* @brief Basic implementation of a SimplePathlossModel
*
* An example config.xml for this AnalogueModel can be the following:
* @verbatim
<AnalogueModel type="SimplePathlossModel">
<!-- Environment parameter of the pathloss formula
If ommited default value is 3.5-->
<parameter name="alpha" type="double" value="3.5"/>
</AnalogueModel>
@endverbatim
*
* @ingroup analogueModels
*/
class VEINS_API SimplePathlossModel : public AnalogueModel {
protected:
/** @brief Path loss coefficient. **/
double pathLossAlphaHalf;
/** @brief Information needed about the playground */
const bool useTorus;
/** @brief The size of the playground.*/
const Coord& playgroundSize;
public:
/**
* @brief Initializes the analogue model. playgroundSize
* need to be valid as long as this instance exists.
*
* The constructor needs some specific knowledge in order to create
* its mapping properly:
*
* @param owner pointer to the cComponent that owns this AnalogueModel
* @param alpha the coefficient alpha (specified e.g. in config.xml and
* passed in constructor call)
* @param useTorus information about the playground the host is moving in
* @param playgroundSize information about the playground the host is
* moving in
*/
SimplePathlossModel(cComponent* owner, double alpha, bool useTorus, const Coord& playgroundSize)
: AnalogueModel(owner)
, pathLossAlphaHalf(alpha * 0.5)
, useTorus(useTorus)
, playgroundSize(playgroundSize)
{
}
/**
* @brief Filters a specified AirFrame's Signal by adding an attenuation
* over time to the Signal.
*/
void filterSignal(Signal*) override;
bool neverIncreasesPower() override
{
return true;
}
};
} // namespace veins
| 3,213 | 30.821782 | 101 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/TwoRayInterferenceModel.cc | //
// Copyright (C) 2011 Stefan Joerer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/TwoRayInterferenceModel.h"
#include "veins/base/messages/AirFrame_m.h"
using namespace veins;
void TwoRayInterferenceModel::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
const Coord senderPos2D(senderPos.x, senderPos.y);
const Coord receiverPos2D(receiverPos.x, receiverPos.y);
ASSERT(senderPos.z > 0); // make sure send antenna is above ground
ASSERT(receiverPos.z > 0); // make sure receive antenna is above ground
double d = senderPos2D.distance(receiverPos2D);
double ht = senderPos.z, hr = receiverPos.z;
EV_TRACE << "(ht, hr) = (" << ht << ", " << hr << ")" << endl;
double d_dir = sqrt(pow(d, 2) + pow((ht - hr), 2)); // direct distance
double d_ref = sqrt(pow(d, 2) + pow((ht + hr), 2)); // distance via ground reflection
double sin_theta = (ht + hr) / d_ref;
double cos_theta = d / d_ref;
double gamma = (sin_theta - sqrt(epsilon_r - pow(cos_theta, 2))) / (sin_theta + sqrt(epsilon_r - pow(cos_theta, 2)));
Signal attenuation(signal->getSpectrum());
for (uint16_t i = 0; i < signal->getNumValues(); i++) {
double freq = signal->getSpectrum().freqAt(i);
double lambda = BaseWorldUtility::speedOfLight() / freq;
double phi = (2 * M_PI / lambda * (d_dir - d_ref));
double att = pow(4 * M_PI * (d / lambda) * 1 / (sqrt((pow((1 + gamma * cos(phi)), 2) + pow(gamma, 2) * pow(sin(phi), 2)))), 2);
EV_TRACE << "Add attenuation for (freq, lambda, phi, gamma, att) = (" << freq << ", " << lambda << ", " << phi << ", " << gamma << ", " << (1 / att) << ", " << FWMath::mW2dBm(att) << ")" << endl;
attenuation.at(i) = 1 / att;
}
*signal *= attenuation;
}
| 2,734 | 41.734375 | 203 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/TwoRayInterferenceModel.h | //
// Copyright (C) 2011 Stefan Joerer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/base/phyLayer/AnalogueModel.h"
#include "veins/base/modules/BaseWorldUtility.h"
namespace veins {
using veins::AirFrame;
/**
* @brief
* Extended version of Two-Ray Ground path loss model.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* An in-depth description of the model is available at:
* Christoph Sommer and Falko Dressler, "Using the Right Two-Ray Model? A Measurement based Evaluation of PHY Models in VANETs," Proceedings of 17th ACM International Conference on Mobile Computing and Networking (MobiCom 2011), Poster Session, Las Vegas, NV, September 2011.
*
* @author Stefan Joerer
*
* @ingroup analogueModels
*/
class VEINS_API TwoRayInterferenceModel : public AnalogueModel {
public:
TwoRayInterferenceModel(cComponent* owner, double dielectricConstant)
: AnalogueModel(owner)
, epsilon_r(dielectricConstant)
{
}
~TwoRayInterferenceModel() override
{
}
void filterSignal(Signal* signal) override;
protected:
/** @brief stores the dielectric constant used for calculation */
double epsilon_r;
};
} // namespace veins
| 2,102 | 30.863636 | 275 | h |
null | AICP-main/veins/src/veins/modules/analogueModel/VehicleObstacleShadowing.cc | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/analogueModel/VehicleObstacleShadowing.h"
using namespace veins;
VehicleObstacleShadowing::VehicleObstacleShadowing(cComponent* owner, VehicleObstacleControl& vehicleObstacleControl, bool useTorus, const Coord& playgroundSize)
: AnalogueModel(owner)
, vehicleObstacleControl(vehicleObstacleControl)
, useTorus(useTorus)
, playgroundSize(playgroundSize)
{
if (useTorus) throw cRuntimeError("VehicleObstacleShadowing does not work on torus-shaped playgrounds");
}
void VehicleObstacleShadowing::filterSignal(Signal* signal)
{
auto senderPos = signal->getSenderPoa().pos.getPositionAt();
auto receiverPos = signal->getReceiverPoa().pos.getPositionAt();
auto potentialObstacles = vehicleObstacleControl.getPotentialObstacles(signal->getSenderPoa().pos, signal->getReceiverPoa().pos, *signal);
if (potentialObstacles.size() < 1) return;
double senderHeight = senderPos.z;
double receiverHeight = receiverPos.z;
potentialObstacles.insert(potentialObstacles.begin(), std::make_pair(0, senderHeight));
potentialObstacles.emplace_back(senderPos.distance(receiverPos), receiverHeight);
auto attenuationDB = VehicleObstacleControl::getVehicleAttenuationDZ(potentialObstacles, Signal(signal->getSpectrum()));
EV_TRACE << "t=" << simTime() << ": Attenuation by vehicles is " << attenuationDB << std::endl;
// convert from "dB loss" to a multiplicative factor
Signal attenuation(attenuationDB.getSpectrum());
for (uint16_t i = 0; i < attenuation.getNumValues(); i++) {
attenuation.at(i) = pow(10.0, -attenuationDB.at(i) / 10.0);
}
*signal *= attenuation;
}
| 2,570 | 40.467742 | 161 | cc |
null | AICP-main/veins/src/veins/modules/analogueModel/VehicleObstacleShadowing.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/base/phyLayer/AnalogueModel.h"
#include "veins/base/modules/BaseWorldUtility.h"
#include "veins/modules/obstacle/VehicleObstacleControl.h"
#include "veins/base/utils/Move.h"
#include "veins/base/messages/AirFrame_m.h"
using veins::AirFrame;
using veins::VehicleObstacleControl;
#include <cstdlib>
namespace veins {
/**
* @brief Basic implementation of a VehicleObstacleShadowing that uses
* SimplePathlossConstMapping (that is subclassed from SimpleConstMapping) as attenuation-Mapping.
*
* @ingroup analogueModels
*/
class VEINS_API VehicleObstacleShadowing : public AnalogueModel {
protected:
/** @brief reference to global VehicleObstacleControl instance */
VehicleObstacleControl& vehicleObstacleControl;
/** @brief Information needed about the playground */
const bool useTorus;
/** @brief The size of the playground.*/
const Coord& playgroundSize;
public:
/**
* @brief Initializes the analogue model. myMove and playgroundSize
* need to be valid as long as this instance exists.
*
* The constructor needs some specific knowledge in order to create
* its mapping properly:
*
* @param owner pointer to the cComponent that owns this AnalogueModel
* @param vehicleObstacleControl reference to global VehicleObstacleControl module
* @param useTorus information about the playground the host is moving in
* @param playgroundSize information about the playground the host is moving in
*/
VehicleObstacleShadowing(cComponent* owner, VehicleObstacleControl& vehicleObstacleControl, bool useTorus, const Coord& playgroundSize);
/**
* @brief Filters a specified Signal by adding an attenuation
* over time to the Signal.
*/
void filterSignal(Signal* signal) override;
bool neverIncreasesPower() override
{
return true;
}
};
} // namespace veins
| 2,820 | 32.987952 | 140 | h |
null | AICP-main/veins/src/veins/modules/application/ieee80211p/DemoBaseApplLayer.cc | //
// Copyright (C) 2011 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h"
using namespace veins;
void DemoBaseApplLayer::initialize(int stage)
{
BaseApplLayer::initialize(stage);
if (stage == 0) {
// initialize pointers to other modules
if (FindModule<TraCIMobility*>::findSubModule(getParentModule())) {
mobility = TraCIMobilityAccess().get(getParentModule());
traci = mobility->getCommandInterface();
traciVehicle = mobility->getVehicleCommandInterface();
}
else {
traci = nullptr;
mobility = nullptr;
traciVehicle = nullptr;
}
annotations = AnnotationManagerAccess().getIfExists();
ASSERT(annotations);
mac = FindModule<DemoBaseApplLayerToMac1609_4Interface*>::findSubModule(getParentModule());
ASSERT(mac);
// read parameters
headerLength = par("headerLength");
sendBeacons = par("sendBeacons").boolValue();
beaconLengthBits = par("beaconLengthBits");
beaconUserPriority = par("beaconUserPriority");
beaconInterval = par("beaconInterval");
dataLengthBits = par("dataLengthBits");
dataOnSch = par("dataOnSch").boolValue();
dataUserPriority = par("dataUserPriority");
wsaInterval = par("wsaInterval").doubleValue();
currentOfferedServiceId = -1;
isParked = false;
findHost()->subscribe(BaseMobility::mobilityStateChangedSignal, this);
findHost()->subscribe(TraCIMobility::parkingStateChangedSignal, this);
sendBeaconEvt = new cMessage("beacon evt", SEND_BEACON_EVT);
sendWSAEvt = new cMessage("wsa evt", SEND_WSA_EVT);
generatedBSMs = 0;
generatedWSAs = 0;
generatedWSMs = 0;
receivedBSMs = 0;
receivedWSAs = 0;
receivedWSMs = 0;
}
else if (stage == 1) {
// store MAC address for quick access
myId = mac->getMACAddress();
// simulate asynchronous channel access
if (dataOnSch == true && !mac->isChannelSwitchingActive()) {
dataOnSch = false;
EV_ERROR << "App wants to send data on SCH but MAC doesn't use any SCH. Sending all data on CCH" << std::endl;
}
simtime_t firstBeacon = simTime();
if (par("avoidBeaconSynchronization").boolValue() == true) {
simtime_t randomOffset = dblrand() * beaconInterval;
firstBeacon = simTime() + randomOffset;
if (mac->isChannelSwitchingActive() == true) {
if (beaconInterval.raw() % (mac->getSwitchingInterval().raw() * 2)) {
EV_ERROR << "The beacon interval (" << beaconInterval << ") is smaller than or not a multiple of one synchronization interval (" << 2 * mac->getSwitchingInterval() << "). This means that beacons are generated during SCH intervals" << std::endl;
}
firstBeacon = computeAsynchronousSendingTime(beaconInterval, ChannelType::control);
}
if (sendBeacons) {
scheduleAt(firstBeacon, sendBeaconEvt);
}
}
}
}
simtime_t DemoBaseApplLayer::computeAsynchronousSendingTime(simtime_t interval, ChannelType chan)
{
/*
* avoid that periodic messages for one channel type are scheduled in the other channel interval
* when alternate access is enabled in the MAC
*/
simtime_t randomOffset = dblrand() * beaconInterval;
simtime_t firstEvent;
simtime_t switchingInterval = mac->getSwitchingInterval(); // usually 0.050s
simtime_t nextCCH;
/*
* start event earliest in next CCH (or SCH) interval. For alignment, first find the next CCH interval
* To find out next CCH, go back to start of current interval and add two or one intervals
* depending on type of current interval
*/
if (mac->isCurrentChannelCCH()) {
nextCCH = simTime() - SimTime().setRaw(simTime().raw() % switchingInterval.raw()) + switchingInterval * 2;
}
else {
nextCCH = simTime() - SimTime().setRaw(simTime().raw() % switchingInterval.raw()) + switchingInterval;
}
firstEvent = nextCCH + randomOffset;
// check if firstEvent lies within the correct interval and, if not, move to previous interval
if (firstEvent.raw() % (2 * switchingInterval.raw()) > switchingInterval.raw()) {
// firstEvent is within a sch interval
if (chan == ChannelType::control) firstEvent -= switchingInterval;
}
else {
// firstEvent is within a cch interval, so adjust for SCH messages
if (chan == ChannelType::service) firstEvent += switchingInterval;
}
return firstEvent;
}
void DemoBaseApplLayer::populateWSM(BaseFrame1609_4* wsm, LAddress::L2Type rcvId, int serial)
{
wsm->setRecipientAddress(rcvId);
wsm->setBitLength(headerLength);
if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(wsm)) {
bsm->setSenderPos(curPosition);
bsm->setAngle(mobility->getHeading().getRad());
bsm->setSenderSpeed(curSpeed);
bsm->setPsid(-1);
bsm->setChannelNumber(static_cast<int>(Channel::cch));
bsm->addBitLength(beaconLengthBits);
wsm->setUserPriority(beaconUserPriority);
}
else if (DemoServiceAdvertisment* wsa = dynamic_cast<DemoServiceAdvertisment*>(wsm)) {
wsa->setChannelNumber(static_cast<int>(Channel::cch));
wsa->setTargetChannel(static_cast<int>(currentServiceChannel));
wsa->setPsid(currentOfferedServiceId);
wsa->setServiceDescription(currentServiceDescription.c_str());
}
else {
if (dataOnSch)
wsm->setChannelNumber(static_cast<int>(Channel::sch1)); // will be rewritten at Mac1609_4 to actual Service Channel. This is just so no controlInfo is needed
else
wsm->setChannelNumber(static_cast<int>(Channel::cch));
wsm->addBitLength(dataLengthBits);
wsm->setUserPriority(dataUserPriority);
}
}
void DemoBaseApplLayer::receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details)
{
Enter_Method_Silent();
if (signalID == BaseMobility::mobilityStateChangedSignal) {
handlePositionUpdate(obj);
}
else if (signalID == TraCIMobility::parkingStateChangedSignal) {
handleParkingUpdate(obj);
}
}
void DemoBaseApplLayer::handlePositionUpdate(cObject* obj)
{
ChannelMobilityPtrType const mobility = check_and_cast<ChannelMobilityPtrType>(obj);
curPosition = mobility->getPositionAt(simTime());
curSpeed = mobility->getCurrentSpeed();
}
void DemoBaseApplLayer::handleParkingUpdate(cObject* obj)
{
isParked = mobility->getParkingState();
}
void DemoBaseApplLayer::handleLowerMsg(cMessage* msg)
{
BaseFrame1609_4* wsm = dynamic_cast<BaseFrame1609_4*>(msg);
ASSERT(wsm);
if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(wsm)) {
receivedBSMs++;
onBSM(bsm);
}
else if (DemoServiceAdvertisment* wsa = dynamic_cast<DemoServiceAdvertisment*>(wsm)) {
receivedWSAs++;
onWSA(wsa);
}
else {
receivedWSMs++;
onWSM(wsm);
}
delete (msg);
}
void DemoBaseApplLayer::handleSelfMsg(cMessage* msg)
{
switch (msg->getKind()) {
case SEND_BEACON_EVT: {
DemoSafetyMessage* bsm = new DemoSafetyMessage();
populateWSM(bsm);
sendDown(bsm);
scheduleAt(simTime() + beaconInterval, sendBeaconEvt);
break;
}
case SEND_WSA_EVT: {
DemoServiceAdvertisment* wsa = new DemoServiceAdvertisment();
populateWSM(wsa);
sendDown(wsa);
scheduleAt(simTime() + wsaInterval, sendWSAEvt);
break;
}
default: {
if (msg) EV_WARN << "APP: Error: Got Self Message of unknown kind! Name: " << msg->getName() << endl;
break;
}
}
}
void DemoBaseApplLayer::finish()
{
recordScalar("generatedWSMs", generatedWSMs);
recordScalar("receivedWSMs", receivedWSMs);
recordScalar("generatedBSMs", generatedBSMs);
recordScalar("receivedBSMs", receivedBSMs);
recordScalar("generatedWSAs", generatedWSAs);
recordScalar("receivedWSAs", receivedWSAs);
}
DemoBaseApplLayer::~DemoBaseApplLayer()
{
cancelAndDelete(sendBeaconEvt);
cancelAndDelete(sendWSAEvt);
findHost()->unsubscribe(BaseMobility::mobilityStateChangedSignal, this);
}
void DemoBaseApplLayer::startService(Channel channel, int serviceId, std::string serviceDescription)
{
if (sendWSAEvt->isScheduled()) {
throw cRuntimeError("Starting service although another service was already started");
}
mac->changeServiceChannel(channel);
currentOfferedServiceId = serviceId;
currentServiceChannel = channel;
currentServiceDescription = serviceDescription;
simtime_t wsaTime = computeAsynchronousSendingTime(wsaInterval, ChannelType::control);
scheduleAt(wsaTime, sendWSAEvt);
}
void DemoBaseApplLayer::stopService()
{
cancelEvent(sendWSAEvt);
currentOfferedServiceId = -1;
}
void DemoBaseApplLayer::sendDown(cMessage* msg)
{
checkAndTrackPacket(msg);
BaseApplLayer::sendDown(msg);
}
void DemoBaseApplLayer::sendDelayedDown(cMessage* msg, simtime_t delay)
{
checkAndTrackPacket(msg);
BaseApplLayer::sendDelayedDown(msg, delay);
}
void DemoBaseApplLayer::checkAndTrackPacket(cMessage* msg)
{
if (dynamic_cast<DemoSafetyMessage*>(msg)) {
EV_TRACE << "sending down a BSM" << std::endl;
generatedBSMs++;
}
else if (dynamic_cast<DemoServiceAdvertisment*>(msg)) {
EV_TRACE << "sending down a WSA" << std::endl;
generatedWSAs++;
}
else if (dynamic_cast<BaseFrame1609_4*>(msg)) {
EV_TRACE << "sending down a wsm" << std::endl;
generatedWSMs++;
}
}
| 10,732 | 32.540625 | 265 | cc |
null | AICP-main/veins/src/veins/modules/application/ieee80211p/DemoBaseApplLayer.h | //
// Copyright (C) 2016 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <map>
#include "veins/base/modules/BaseApplLayer.h"
#include "veins/modules/utility/Consts80211p.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
#include "veins/modules/messages/DemoServiceAdvertisement_m.h"
#include "veins/modules/messages/DemoSafetyMessage_m.h"
#include "veins/base/connectionManager/ChannelAccess.h"
#include "veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h"
#include "veins/modules/mobility/traci/TraCIMobility.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
namespace veins {
using veins::AnnotationManager;
using veins::AnnotationManagerAccess;
using veins::TraCICommandInterface;
using veins::TraCIMobility;
using veins::TraCIMobilityAccess;
/**
* @brief
* Demo application layer base class.
*
* @author David Eckhoff
*
* @ingroup applLayer
*
* @see DemoBaseApplLayer
* @see Mac1609_4
* @see PhyLayer80211p
* @see Decider80211p
*/
class VEINS_API DemoBaseApplLayer : public BaseApplLayer {
public:
~DemoBaseApplLayer() override;
void initialize(int stage) override;
void finish() override;
void receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) override;
enum DemoApplMessageKinds {
SEND_BEACON_EVT,
SEND_WSA_EVT
};
protected:
/** @brief handle messages from below and calls the onWSM, onBSM, and onWSA functions accordingly */
void handleLowerMsg(cMessage* msg) override;
/** @brief handle self messages */
void handleSelfMsg(cMessage* msg) override;
/** @brief sets all the necessary fields in the WSM, BSM, or WSA. */
virtual void populateWSM(BaseFrame1609_4* wsm, LAddress::L2Type rcvId = LAddress::L2BROADCAST(), int serial = 0);
/** @brief this function is called upon receiving a BaseFrame1609_4 */
virtual void onWSM(BaseFrame1609_4* wsm){};
/** @brief this function is called upon receiving a DemoSafetyMessage, also referred to as a beacon */
virtual void onBSM(DemoSafetyMessage* bsm){};
/** @brief this function is called upon receiving a DemoServiceAdvertisement */
virtual void onWSA(DemoServiceAdvertisment* wsa){};
/** @brief this function is called every time the vehicle receives a position update signal */
virtual void handlePositionUpdate(cObject* obj);
/** @brief this function is called every time the vehicle parks or starts moving again */
virtual void handleParkingUpdate(cObject* obj);
/** @brief This will start the periodic advertising of the new service on the CCH
*
* @param channel the channel on which the service is provided
* @param serviceId a service ID to be used with the service
* @param serviceDescription a literal description of the service
*/
virtual void startService(Channel channel, int serviceId, std::string serviceDescription);
/** @brief stopping the service and advertising for it */
virtual void stopService();
/** @brief compute a point in time that is guaranteed to be in the correct channel interval plus a random offset
*
* @param interval the interval length of the periodic message
* @param chantype the type of channel, either type_CCH or type_SCH
*/
virtual simtime_t computeAsynchronousSendingTime(simtime_t interval, ChannelType chantype);
/**
* @brief overloaded for error handling and stats recording purposes
*
* @param msg the message to be sent. Must be a WSM/BSM/WSA
*/
virtual void sendDown(cMessage* msg);
/**
* @brief overloaded for error handling and stats recording purposes
*
* @param msg the message to be sent. Must be a WSM/BSM/WSA
* @param delay the delay for the message
*/
virtual void sendDelayedDown(cMessage* msg, simtime_t delay);
/**
* @brief helper function for error handling and stats recording purposes
*
* @param msg the message to be checked and tracked
*/
virtual void checkAndTrackPacket(cMessage* msg);
protected:
/* pointers ill be set when used with TraCIMobility */
TraCIMobility* mobility;
TraCICommandInterface* traci;
TraCICommandInterface::Vehicle* traciVehicle;
AnnotationManager* annotations;
DemoBaseApplLayerToMac1609_4Interface* mac;
/* support for parking currently only works with TraCI */
bool isParked;
/* BSM (beacon) settings */
uint32_t beaconLengthBits;
uint32_t beaconUserPriority;
simtime_t beaconInterval;
bool sendBeacons;
/* WSM (data) settings */
uint32_t dataLengthBits;
uint32_t dataUserPriority;
bool dataOnSch;
/* WSA settings */
int currentOfferedServiceId;
std::string currentServiceDescription;
Channel currentServiceChannel;
simtime_t wsaInterval;
/* state of the vehicle */
Coord curPosition;
Coord curSpeed;
LAddress::L2Type myId = 0;
int mySCH;
/* stats */
uint32_t generatedWSMs;
uint32_t generatedWSAs;
uint32_t generatedBSMs;
uint32_t receivedWSMs;
uint32_t receivedWSAs;
uint32_t receivedBSMs;
/* messages for periodic events such as beacon and WSA transmissions */
cMessage* sendBeaconEvt;
cMessage* sendWSAEvt;
};
} // namespace veins
| 6,159 | 32.11828 | 117 | h |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11p.cc | //
// Copyright (C) 2006-2011 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/application/traci/TraCIDemo11p.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"
using namespace veins;
Define_Module(veins::TraCIDemo11p);
void TraCIDemo11p::initialize(int stage)
{
DemoBaseApplLayer::initialize(stage);
if (stage == 0) {
sentMessage = false;
lastDroveAt = simTime();
currentSubscribedServiceId = -1;
}
}
void TraCIDemo11p::onBSM(DemoSafetyMessage* bsm){
//if (!sentMessage) {
//sentMessage = true;
// repeat the received traffic update once in 2 seconds plus some random delay
bsm->setSerial(0);
scheduleAt(simTime() + 0.1 + uniform(0.01, 0.2), bsm->dup());
//}
}
void TraCIDemo11p::onWSA(DemoServiceAdvertisment* wsa)
{
if (currentSubscribedServiceId == -1) {
mac->changeServiceChannel(static_cast<Channel>(wsa->getTargetChannel()));
currentSubscribedServiceId = wsa->getPsid();
if (currentOfferedServiceId != wsa->getPsid()) {
stopService();
startService(static_cast<Channel>(wsa->getTargetChannel()), wsa->getPsid(), "Mirrored Traffic Service");
}
}
}
void TraCIDemo11p::onWSM(BaseFrame1609_4* frame)
{
TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame);
findHost()->getDisplayString().setTagArg("i", 1, "green");
if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getDemoData(), 9999);
if (!sentMessage) {
sentMessage = true;
// repeat the received traffic update once in 2 seconds plus some random delay
wsm->setSenderAddress(myId);
wsm->setSerial(3);
scheduleAt(simTime() + 0.01 + uniform(0.01, 0.2), wsm->dup());
}
}
void TraCIDemo11p::handleSelfMsg(cMessage* msg)
{
if (TraCIDemo11pMessage* wsm = dynamic_cast<TraCIDemo11pMessage*>(msg)) {
// send this message on the service channel until the counter is 3 or higher.
// this code only runs when channel switching is enabled
sendDown(wsm->dup());
wsm->setSerial(wsm->getSerial() + 1);
if (wsm->getSerial() >= 3) {
// stop service advertisements
stopService();
delete (wsm);
}
else {
scheduleAt(simTime() + 1, wsm);
}
}
else if (DemoSafetyMessage* bsm = dynamic_cast<DemoSafetyMessage*>(msg)){
bsm->setSerial(bsm->getSerial() + 1);
// hop limit = 2, distance limit = 100, heading direction diff limit = 30"
if (bsm->getSerial() >= 3|| bsm->getSenderPos().distance(curPosition) >= 100 || std::abs(bsm->getAngle()-mobility->getHeading().getRad())>=0.52) {
//if (bsm->getSerial() >= 3 || bsm->getSenderPos().distance(curPosition) >= 100){
// stop service advertisements
stopService();
delete (bsm);
}
else {
sendDown(bsm->dup());
}
}
else {
DemoBaseApplLayer::handleSelfMsg(msg);
}
}
void TraCIDemo11p::handlePositionUpdate(cObject* obj)
{
DemoBaseApplLayer::handlePositionUpdate(obj);
// stopped for for at least 10s?
if (mobility->getSpeed() < 1) {
if (simTime() - lastDroveAt >= 10 && sentMessage == false) {
findHost()->getDisplayString().setTagArg("i", 1, "red");
sentMessage = true;
TraCIDemo11pMessage* wsm = new TraCIDemo11pMessage();
populateWSM(wsm);
wsm->setDemoData(mobility->getRoadId().c_str());
// host is standing still due to crash
if (dataOnSch) {
startService(Channel::sch2, 42, "Traffic Information Service");
// started service and server advertising, schedule message to self to send later
scheduleAt(computeAsynchronousSendingTime(1, ChannelType::service), wsm);
}
else {
// send right away on CCH, because channel switching is disabled
sendDown(wsm);
}
}
}
else {
lastDroveAt = simTime();
}
}
| 4,994 | 33.93007 | 154 | cc |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11p.h | //
// Copyright (C) 2006-2011 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h"
namespace veins {
/**
* @brief
* A tutorial demo for TraCI. When the car is stopped for longer than 10 seconds
* it will send a message out to other cars containing the blocked road id.
* Receiving cars will then trigger a reroute via TraCI.
* When channel switching between SCH and CCH is enabled on the MAC, the message is
* instead send out on a service channel following a Service Advertisement
* on the CCH.
*
* @author Christoph Sommer : initial DemoApp
* @author David Eckhoff : rewriting, moving functionality to DemoBaseApplLayer, adding WSA
*
*/
class VEINS_API TraCIDemo11p : public DemoBaseApplLayer {
public:
void initialize(int stage) override;
protected:
simtime_t lastDroveAt;
bool sentMessage;
int currentSubscribedServiceId;
protected:
void onBSM(DemoSafetyMessage* bsm) override;
void onWSM(BaseFrame1609_4* wsm) override;
void onWSA(DemoServiceAdvertisment* wsa) override;
void handleSelfMsg(cMessage* msg) override;
void handlePositionUpdate(cObject* obj) override;
};
} // namespace veins
| 2,061 | 32.258065 | 91 | h |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11pMessage_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/application/traci/TraCIDemo11pMessage.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "TraCIDemo11pMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(TraCIDemo11pMessage)
TraCIDemo11pMessage::TraCIDemo11pMessage(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind)
{
this->senderAddress = -1;
this->serial = 0;
}
TraCIDemo11pMessage::TraCIDemo11pMessage(const TraCIDemo11pMessage& other) : ::veins::BaseFrame1609_4(other)
{
copy(other);
}
TraCIDemo11pMessage::~TraCIDemo11pMessage()
{
}
TraCIDemo11pMessage& TraCIDemo11pMessage::operator=(const TraCIDemo11pMessage& other)
{
if (this==&other) return *this;
::veins::BaseFrame1609_4::operator=(other);
copy(other);
return *this;
}
void TraCIDemo11pMessage::copy(const TraCIDemo11pMessage& other)
{
this->demoData = other.demoData;
this->senderAddress = other.senderAddress;
this->serial = other.serial;
}
void TraCIDemo11pMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::BaseFrame1609_4::parsimPack(b);
doParsimPacking(b,this->demoData);
doParsimPacking(b,this->senderAddress);
doParsimPacking(b,this->serial);
}
void TraCIDemo11pMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::BaseFrame1609_4::parsimUnpack(b);
doParsimUnpacking(b,this->demoData);
doParsimUnpacking(b,this->senderAddress);
doParsimUnpacking(b,this->serial);
}
const char * TraCIDemo11pMessage::getDemoData() const
{
return this->demoData.c_str();
}
void TraCIDemo11pMessage::setDemoData(const char * demoData)
{
this->demoData = demoData;
}
LAddress::L2Type& TraCIDemo11pMessage::getSenderAddress()
{
return this->senderAddress;
}
void TraCIDemo11pMessage::setSenderAddress(const LAddress::L2Type& senderAddress)
{
this->senderAddress = senderAddress;
}
int TraCIDemo11pMessage::getSerial() const
{
return this->serial;
}
void TraCIDemo11pMessage::setSerial(int serial)
{
this->serial = serial;
}
class TraCIDemo11pMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
TraCIDemo11pMessageDescriptor();
virtual ~TraCIDemo11pMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(TraCIDemo11pMessageDescriptor)
TraCIDemo11pMessageDescriptor::TraCIDemo11pMessageDescriptor() : omnetpp::cClassDescriptor("veins::TraCIDemo11pMessage", "veins::BaseFrame1609_4")
{
propertynames = nullptr;
}
TraCIDemo11pMessageDescriptor::~TraCIDemo11pMessageDescriptor()
{
delete[] propertynames;
}
bool TraCIDemo11pMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<TraCIDemo11pMessage *>(obj)!=nullptr;
}
const char **TraCIDemo11pMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *TraCIDemo11pMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int TraCIDemo11pMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount() : 3;
}
unsigned int TraCIDemo11pMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISCOMPOUND,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *TraCIDemo11pMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"demoData",
"senderAddress",
"serial",
};
return (field>=0 && field<3) ? fieldNames[field] : nullptr;
}
int TraCIDemo11pMessageDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='d' && strcmp(fieldName, "demoData")==0) return base+0;
if (fieldName[0]=='s' && strcmp(fieldName, "senderAddress")==0) return base+1;
if (fieldName[0]=='s' && strcmp(fieldName, "serial")==0) return base+2;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *TraCIDemo11pMessageDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"LAddress::L2Type",
"int",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr;
}
const char **TraCIDemo11pMessageDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *TraCIDemo11pMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int TraCIDemo11pMessageDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *TraCIDemo11pMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string TraCIDemo11pMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getDemoData());
case 1: {std::stringstream out; out << pp->getSenderAddress(); return out.str();}
case 2: return long2string(pp->getSerial());
default: return "";
}
}
bool TraCIDemo11pMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp;
switch (field) {
case 0: pp->setDemoData((value)); return true;
case 2: pp->setSerial(string2long(value)); return true;
default: return false;
}
}
const char *TraCIDemo11pMessageDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 1: return omnetpp::opp_typename(typeid(LAddress::L2Type));
default: return nullptr;
};
}
void *TraCIDemo11pMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
TraCIDemo11pMessage *pp = (TraCIDemo11pMessage *)object; (void)pp;
switch (field) {
case 1: return (void *)(&pp->getSenderAddress()); break;
default: return nullptr;
}
}
} // namespace veins
| 16,188 | 31.184891 | 146 | cc |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemo11pMessage_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/application/traci/TraCIDemo11pMessage.msg.
//
#ifndef __VEINS_TRACIDEMO11PMESSAGE_M_H
#define __VEINS_TRACIDEMO11PMESSAGE_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/utils/Coord.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
#include "veins/base/utils/SimpleAddress.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/application/traci/TraCIDemo11pMessage.msg:35</tt> by nedtool.
* <pre>
* packet TraCIDemo11pMessage extends BaseFrame1609_4
* {
* string demoData;
* LAddress::L2Type senderAddress = -1;
* int serial = 0;
* }
* </pre>
*/
class VEINS_API TraCIDemo11pMessage : public ::veins::BaseFrame1609_4
{
protected:
::omnetpp::opp_string demoData;
LAddress::L2Type senderAddress;
int serial;
private:
void copy(const TraCIDemo11pMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TraCIDemo11pMessage&);
public:
TraCIDemo11pMessage(const char *name=nullptr, short kind=0);
TraCIDemo11pMessage(const TraCIDemo11pMessage& other);
virtual ~TraCIDemo11pMessage();
TraCIDemo11pMessage& operator=(const TraCIDemo11pMessage& other);
virtual TraCIDemo11pMessage *dup() const override {return new TraCIDemo11pMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual const char * getDemoData() const;
virtual void setDemoData(const char * demoData);
virtual LAddress::L2Type& getSenderAddress();
virtual const LAddress::L2Type& getSenderAddress() const {return const_cast<TraCIDemo11pMessage*>(this)->getSenderAddress();}
virtual void setSenderAddress(const LAddress::L2Type& senderAddress);
virtual int getSerial() const;
virtual void setSerial(int serial);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const TraCIDemo11pMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, TraCIDemo11pMessage& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_TRACIDEMO11PMESSAGE_M_H
| 2,809 | 30.222222 | 129 | h |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemoRSU11p.cc | //
// Copyright (C) 2016 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/application/traci/TraCIDemoRSU11p.h"
#include "veins/modules/application/traci/TraCIDemo11pMessage_m.h"
using namespace veins;
Define_Module(veins::TraCIDemoRSU11p);
void TraCIDemoRSU11p::onWSA(DemoServiceAdvertisment* wsa)
{
// if this RSU receives a WSA for service 42, it will tune to the chan
if (wsa->getPsid() == 42) {
mac->changeServiceChannel(static_cast<Channel>(wsa->getTargetChannel()));
}
}
void TraCIDemoRSU11p::onWSM(BaseFrame1609_4* frame)
{
TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame);
// this rsu repeats the received traffic update in 2 seconds plus some random delay
sendDelayedDown(wsm->dup(), 2 + uniform(0.01, 0.2));
}
| 1,628 | 34.413043 | 87 | cc |
null | AICP-main/veins/src/veins/modules/application/traci/TraCIDemoRSU11p.h | //
// Copyright (C) 2016 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/modules/application/ieee80211p/DemoBaseApplLayer.h"
namespace veins {
/**
* Small RSU Demo using 11p
*/
class VEINS_API TraCIDemoRSU11p : public DemoBaseApplLayer {
protected:
void onWSM(BaseFrame1609_4* wsm) override;
void onWSA(DemoServiceAdvertisment* wsa) override;
};
} // namespace veins
| 1,235 | 30.692308 | 76 | h |
null | AICP-main/veins/src/veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h | //
// Copyright (C) 2011 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/base/utils/NetwToMacControlInfo.h"
#include "veins/modules/utility/Consts80211p.h"
namespace veins {
/**
* @brief
* Interface between DemoBaseApplLayer Layer and Mac1609_4
*
* @author David Eckhoff
*
* @ingroup macLayer
*/
class VEINS_API DemoBaseApplLayerToMac1609_4Interface {
public:
virtual bool isChannelSwitchingActive() = 0;
virtual simtime_t getSwitchingInterval() = 0;
virtual bool isCurrentChannelCCH() = 0;
virtual void changeServiceChannel(Channel channelNumber) = 0;
virtual ~DemoBaseApplLayerToMac1609_4Interface(){};
/**
* @brief Returns the MAC address of this MAC module.
*/
virtual const LAddress::L2Type& getMACAddress() = 0;
};
} // namespace veins
| 1,647 | 27.912281 | 76 | h |
null | AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac1609_4.cc | //
// Copyright (C) 2016 David Eckhoff <[email protected]>
// Copyright (C) 2018 Fabian Bronner <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mac/ieee80211p/Mac1609_4.h"
#include <iterator>
#include "veins/modules/phy/DeciderResult80211.h"
#include "veins/base/phyLayer/PhyToMacControlInfo.h"
#include "veins/modules/messages/PhyControlMessage_m.h"
#include "veins/modules/messages/AckTimeOutMessage_m.h"
using namespace veins;
using std::unique_ptr;
Define_Module(veins::Mac1609_4);
const simsignal_t Mac1609_4::sigChannelBusy = registerSignal("org_car2x_veins_modules_mac_sigChannelBusy");
const simsignal_t Mac1609_4::sigCollision = registerSignal("org_car2x_veins_modules_mac_sigCollision");
void Mac1609_4::initialize(int stage)
{
BaseMacLayer::initialize(stage);
if (stage == 0) {
phy11p = FindModule<Mac80211pToPhy11pInterface*>::findSubModule(getParentModule());
ASSERT(phy11p);
// this is required to circumvent double precision issues with constants from CONST80211p.h
ASSERT(simTime().getScaleExp() == -12);
txPower = par("txPower").doubleValue();
setParametersForBitrate(par("bitrate"));
// unicast parameters
dot11RTSThreshold = par("dot11RTSThreshold");
dot11ShortRetryLimit = par("dot11ShortRetryLimit");
dot11LongRetryLimit = par("dot11LongRetryLimit");
ackLength = par("ackLength");
useAcks = par("useAcks").boolValue();
ackErrorRate = par("ackErrorRate").doubleValue();
rxStartIndication = false;
ignoreChannelState = false;
waitUntilAckRXorTimeout = false;
stopIgnoreChannelStateMsg = new cMessage("ChannelStateMsg");
myId = getParentModule()->getParentModule()->getFullPath();
// create two edca systems
myEDCA[ChannelType::control] = make_unique<EDCA>(this, ChannelType::control, par("queueSize"));
myEDCA[ChannelType::control]->myId = myId;
myEDCA[ChannelType::control]->myId.append(" CCH");
myEDCA[ChannelType::control]->createQueue(2, (((CWMIN_11P + 1) / 4) - 1), (((CWMIN_11P + 1) / 2) - 1), AC_VO);
myEDCA[ChannelType::control]->createQueue(3, (((CWMIN_11P + 1) / 2) - 1), CWMIN_11P, AC_VI);
myEDCA[ChannelType::control]->createQueue(6, CWMIN_11P, CWMAX_11P, AC_BE);
myEDCA[ChannelType::control]->createQueue(9, CWMIN_11P, CWMAX_11P, AC_BK);
myEDCA[ChannelType::service] = make_unique<EDCA>(this, ChannelType::service, par("queueSize"));
myEDCA[ChannelType::service]->myId = myId;
myEDCA[ChannelType::service]->myId.append(" SCH");
myEDCA[ChannelType::service]->createQueue(2, (((CWMIN_11P + 1) / 4) - 1), (((CWMIN_11P + 1) / 2) - 1), AC_VO);
myEDCA[ChannelType::service]->createQueue(3, (((CWMIN_11P + 1) / 2) - 1), CWMIN_11P, AC_VI);
myEDCA[ChannelType::service]->createQueue(6, CWMIN_11P, CWMAX_11P, AC_BE);
myEDCA[ChannelType::service]->createQueue(9, CWMIN_11P, CWMAX_11P, AC_BK);
useSCH = par("useServiceChannel").boolValue();
if (useSCH) {
if (useAcks) throw cRuntimeError("Unicast model does not support channel switching");
// set the initial service channel
int serviceChannel = par("serviceChannel");
switch (serviceChannel) {
case 1:
mySCH = Channel::sch1;
break;
case 2:
mySCH = Channel::sch2;
break;
case 3:
mySCH = Channel::sch3;
break;
case 4:
mySCH = Channel::sch4;
break;
default:
throw cRuntimeError("Service Channel must be between 1 and 4");
break;
}
}
headerLength = par("headerLength");
nextMacEvent = new cMessage("next Mac Event");
if (useSCH) {
uint64_t currenTime = simTime().raw();
uint64_t switchingTime = SWITCHING_INTERVAL_11P.raw();
double timeToNextSwitch = (double) (switchingTime - (currenTime % switchingTime)) / simTime().getScale();
if ((currenTime / switchingTime) % 2 == 0) {
setActiveChannel(ChannelType::control);
}
else {
setActiveChannel(ChannelType::service);
}
// channel switching active
nextChannelSwitch = new cMessage("Channel Switch");
// add a little bit of offset between all vehicles, but no more than syncOffset
simtime_t offset = dblrand() * par("syncOffset").doubleValue();
scheduleAt(simTime() + offset + timeToNextSwitch, nextChannelSwitch);
}
else {
// no channel switching
nextChannelSwitch = nullptr;
setActiveChannel(ChannelType::control);
}
// stats
statsReceivedPackets = 0;
statsReceivedBroadcasts = 0;
statsSentPackets = 0;
statsSentAcks = 0;
statsTXRXLostPackets = 0;
statsSNIRLostPackets = 0;
statsDroppedPackets = 0;
statsNumTooLittleTime = 0;
statsNumInternalContention = 0;
statsNumBackoff = 0;
statsSlotsBackoff = 0;
statsTotalBusyTime = 0;
idleChannel = true;
lastBusy = simTime();
channelIdle(true);
}
}
void Mac1609_4::handleSelfMsg(cMessage* msg)
{
if (msg == stopIgnoreChannelStateMsg) {
ignoreChannelState = false;
return;
}
if (AckTimeOutMessage* ackTimeOutMsg = dynamic_cast<AckTimeOutMessage*>(msg)) {
handleAckTimeOut(ackTimeOutMsg);
return;
}
if (msg == nextChannelSwitch) {
ASSERT(useSCH);
scheduleAt(simTime() + SWITCHING_INTERVAL_11P, nextChannelSwitch);
switch (activeChannel) {
case ChannelType::control:
EV_TRACE << "CCH --> SCH" << std::endl;
channelBusySelf(false);
setActiveChannel(ChannelType::service);
channelIdle(true);
phy11p->changeListeningChannel(mySCH);
break;
case ChannelType::service:
EV_TRACE << "SCH --> CCH" << std::endl;
channelBusySelf(false);
setActiveChannel(ChannelType::control);
channelIdle(true);
phy11p->changeListeningChannel(Channel::cch);
break;
}
// schedule next channel switch in 50ms
}
else if (msg == nextMacEvent) {
// we actually came to the point where we can send a packet
channelBusySelf(true);
BaseFrame1609_4* pktToSend = myEDCA[activeChannel]->initiateTransmit(lastIdle);
ASSERT(pktToSend);
lastAC = mapUserPriority(pktToSend->getUserPriority());
lastWSM = pktToSend;
EV_TRACE << "MacEvent received. Trying to send packet with priority" << lastAC << std::endl;
// send the packet
Mac80211Pkt* mac = new Mac80211Pkt(pktToSend->getName(), pktToSend->getKind());
if (pktToSend->getRecipientAddress() != LAddress::L2BROADCAST()) {
mac->setDestAddr(pktToSend->getRecipientAddress());
}
else {
mac->setDestAddr(LAddress::L2BROADCAST());
}
mac->setSrcAddr(myMacAddr);
mac->encapsulate(pktToSend->dup());
MCS usedMcs = mcs;
double txPower_mW;
PhyControlMessage* controlInfo = dynamic_cast<PhyControlMessage*>(pktToSend->getControlInfo());
if (controlInfo) {
// if MCS is not specified, just use the default one
MCS explicitMcs = static_cast<MCS>(controlInfo->getMcs());
if (explicitMcs != MCS::undefined) {
usedMcs = explicitMcs;
}
// apply the same principle to tx power
txPower_mW = controlInfo->getTxPower_mW();
if (txPower_mW < 0) {
txPower_mW = txPower;
}
}
else {
txPower_mW = txPower;
}
simtime_t sendingDuration = RADIODELAY_11P + phy11p->getFrameDuration(mac->getBitLength(), usedMcs);
EV_TRACE << "Sending duration will be" << sendingDuration << std::endl;
if ((!useSCH) || (timeLeftInSlot() > sendingDuration)) {
if (useSCH) EV_TRACE << " Time in this slot left: " << timeLeftInSlot() << std::endl;
Channel channelNr = (activeChannel == ChannelType::control) ? Channel::cch : mySCH;
double freq = IEEE80211ChannelFrequencies.at(channelNr);
EV_TRACE << "Sending a Packet. Frequency " << freq << " Priority" << lastAC << std::endl;
sendFrame(mac, RADIODELAY_11P, channelNr, usedMcs, txPower_mW);
// schedule ack timeout for unicast packets
if (pktToSend->getRecipientAddress() != LAddress::L2BROADCAST() && useAcks) {
waitUntilAckRXorTimeout = true;
// PHY-RXSTART.indication should be received within ackWaitTime
// sifs + slot + rx_delay: see 802.11-2012 9.3.2.8 (32us + 13us + 49us = 94us)
simtime_t ackWaitTime(94, SIMTIME_US);
// update id in the retransmit timer
myEDCA[activeChannel]->myQueues[lastAC].ackTimeOut->setWsmId(pktToSend->getTreeId());
simtime_t timeOut = sendingDuration + ackWaitTime;
scheduleAt(simTime() + timeOut, myEDCA[activeChannel]->myQueues[lastAC].ackTimeOut);
}
}
else { // not enough time left now
EV_TRACE << "Too little Time left. This packet cannot be send in this slot." << std::endl;
statsNumTooLittleTime++;
// revoke TXOP
myEDCA[activeChannel]->revokeTxOPs();
delete mac;
channelIdle();
// do nothing. contention will automatically start after channel switch
}
}
}
void Mac1609_4::handleUpperControl(cMessage* msg)
{
ASSERT(false);
}
void Mac1609_4::handleUpperMsg(cMessage* msg)
{
BaseFrame1609_4* thisMsg = check_and_cast<BaseFrame1609_4*>(msg);
t_access_category ac = mapUserPriority(thisMsg->getUserPriority());
EV_TRACE << "Received a message from upper layer for channel " << thisMsg->getChannelNumber() << " Access Category (Priority): " << ac << std::endl;
ChannelType chan;
if (static_cast<Channel>(thisMsg->getChannelNumber()) == Channel::cch) {
chan = ChannelType::control;
}
else {
ASSERT(useSCH);
thisMsg->setChannelNumber(static_cast<int>(mySCH));
chan = ChannelType::service;
}
int num = myEDCA[chan]->queuePacket(ac, thisMsg);
// packet was dropped in Mac
if (num == -1) {
statsDroppedPackets++;
return;
}
// if this packet is not at the front of a new queue we dont have to reevaluate times
EV_TRACE << "sorted packet into queue of EDCA " << static_cast<int>(chan) << " this packet is now at position: " << num << std::endl;
if (chan == activeChannel) {
EV_TRACE << "this packet is for the currently active channel" << std::endl;
}
else {
EV_TRACE << "this packet is NOT for the currently active channel" << std::endl;
}
if (num == 1 && idleChannel == true && chan == activeChannel) {
simtime_t nextEvent = myEDCA[chan]->startContent(lastIdle, guardActive());
if (nextEvent != -1) {
if ((!useSCH) || (nextEvent <= nextChannelSwitch->getArrivalTime())) {
if (nextMacEvent->isScheduled()) {
cancelEvent(nextMacEvent);
}
scheduleAt(nextEvent, nextMacEvent);
EV_TRACE << "Updated nextMacEvent:" << nextMacEvent->getArrivalTime().raw() << std::endl;
}
else {
EV_TRACE << "Too little time in this interval. Will not schedule nextMacEvent" << std::endl;
// it is possible that this queue has an txop. we have to revoke it
myEDCA[activeChannel]->revokeTxOPs();
statsNumTooLittleTime++;
}
}
else {
cancelEvent(nextMacEvent);
}
}
if (num == 1 && idleChannel == false && myEDCA[chan]->myQueues[ac].currentBackoff == 0 && chan == activeChannel) {
myEDCA[chan]->backoff(ac);
}
}
void Mac1609_4::handleLowerControl(cMessage* msg)
{
if (msg->getKind() == MacToPhyInterface::PHY_RX_START) {
rxStartIndication = true;
}
else if (msg->getKind() == MacToPhyInterface::PHY_RX_END_WITH_SUCCESS) {
// PHY_RX_END_WITH_SUCCESS will get packet soon! Nothing to do here
}
else if (msg->getKind() == MacToPhyInterface::PHY_RX_END_WITH_FAILURE) {
// RX failed at phy. Time to retransmit
phy11p->notifyMacAboutRxStart(false);
rxStartIndication = false;
handleRetransmit(lastAC);
}
else if (msg->getKind() == MacToPhyInterface::TX_OVER) {
EV_TRACE << "Successfully transmitted a packet on " << lastAC << std::endl;
phy->setRadioState(Radio::RX);
if (!dynamic_cast<Mac80211Ack*>(lastMac.get())) {
// message was sent
// update EDCA queue. go into post-transmit backoff and set cwCur to cwMin
myEDCA[activeChannel]->postTransmit(lastAC, lastWSM, useAcks);
}
// channel just turned idle.
// don't set the chan to idle. the PHY layer decides, not us.
if (guardActive()) {
throw cRuntimeError("We shouldnt have sent a packet in guard!");
}
}
else if (msg->getKind() == Mac80211pToPhy11pInterface::CHANNEL_BUSY) {
channelBusy();
}
else if (msg->getKind() == Mac80211pToPhy11pInterface::CHANNEL_IDLE) {
// Decider80211p::processSignalEnd() sends up the received packet to MAC followed by control message CHANNEL_IDLE in the same timestamp.
// If we received a unicast frame (first event scheduled by Decider), MAC immediately schedules an ACK message and wants to switch the radio to TX mode.
// So, the notification for channel idle from phy is undesirable and we skip it here.
// After ACK TX is over, PHY will inform the channel status again.
if (ignoreChannelState) {
// Skipping channelidle because we are about to send an ack regardless of the channel state
}
else {
channelIdle();
}
}
else if (msg->getKind() == Decider80211p::BITERROR || msg->getKind() == Decider80211p::COLLISION) {
statsSNIRLostPackets++;
EV_TRACE << "A packet was not received due to biterrors" << std::endl;
}
else if (msg->getKind() == Decider80211p::RECWHILESEND) {
statsTXRXLostPackets++;
EV_TRACE << "A packet was not received because we were sending while receiving" << std::endl;
}
else if (msg->getKind() == MacToPhyInterface::RADIO_SWITCHING_OVER) {
EV_TRACE << "Phylayer said radio switching is done" << std::endl;
}
else if (msg->getKind() == BaseDecider::PACKET_DROPPED) {
phy->setRadioState(Radio::RX);
EV_TRACE << "Phylayer said packet was dropped" << std::endl;
}
else {
EV_WARN << "Invalid control message type (type=NOTHING) : name=" << msg->getName() << " modulesrc=" << msg->getSenderModule()->getFullPath() << "." << std::endl;
ASSERT(false);
}
if (msg->getKind() == Decider80211p::COLLISION) {
emit(sigCollision, true);
}
delete msg;
}
void Mac1609_4::setActiveChannel(ChannelType state)
{
activeChannel = state;
ASSERT(state == ChannelType::control || (useSCH && state == ChannelType::service));
}
void Mac1609_4::finish()
{
for (auto&& p : myEDCA) {
statsNumInternalContention += p.second->statsNumInternalContention;
statsNumBackoff += p.second->statsNumBackoff;
statsSlotsBackoff += p.second->statsSlotsBackoff;
}
recordScalar("ReceivedUnicastPackets", statsReceivedPackets);
recordScalar("ReceivedBroadcasts", statsReceivedBroadcasts);
recordScalar("SentPackets", statsSentPackets);
recordScalar("SentAcknowledgements", statsSentAcks);
recordScalar("SNIRLostPackets", statsSNIRLostPackets);
recordScalar("RXTXLostPackets", statsTXRXLostPackets);
recordScalar("TotalLostPackets", statsSNIRLostPackets + statsTXRXLostPackets);
recordScalar("DroppedPacketsInMac", statsDroppedPackets);
recordScalar("TooLittleTime", statsNumTooLittleTime);
recordScalar("TimesIntoBackoff", statsNumBackoff);
recordScalar("SlotsBackoff", statsSlotsBackoff);
recordScalar("NumInternalContention", statsNumInternalContention);
recordScalar("totalBusyTime", statsTotalBusyTime.dbl());
}
Mac1609_4::~Mac1609_4()
{
if (nextMacEvent) {
cancelAndDelete(nextMacEvent);
nextMacEvent = nullptr;
}
if (nextChannelSwitch) {
cancelAndDelete(nextChannelSwitch);
nextChannelSwitch = nullptr;
}
if (stopIgnoreChannelStateMsg) {
cancelAndDelete(stopIgnoreChannelStateMsg);
stopIgnoreChannelStateMsg = nullptr;
}
};
void Mac1609_4::sendFrame(Mac80211Pkt* frame, simtime_t delay, Channel channelNr, MCS mcs, double txPower_mW)
{
phy->setRadioState(Radio::TX); // give time for the radio to be in Tx state before transmitting
delay = std::max(delay, RADIODELAY_11P); // wait at least for the radio to switch
attachControlInfo(frame, channelNr, mcs, txPower_mW);
check_and_cast<MacToPhyControlInfo11p*>(frame->getControlInfo());
lastMac.reset(frame->dup());
sendDelayed(frame, delay, lowerLayerOut);
if (dynamic_cast<Mac80211Ack*>(frame)) {
statsSentAcks += 1;
}
else {
statsSentPackets += 1;
}
}
void Mac1609_4::attachControlInfo(Mac80211Pkt* mac, Channel channelNr, MCS mcs, double txPower_mW)
{
auto cinfo = new MacToPhyControlInfo11p(channelNr, mcs, txPower_mW);
mac->setControlInfo(cinfo);
}
/* checks if guard is active */
bool Mac1609_4::guardActive() const
{
if (!useSCH) return false;
if (simTime().dbl() - nextChannelSwitch->getSendingTime() <= GUARD_INTERVAL_11P) return true;
return false;
}
/* returns the time until the guard is over */
simtime_t Mac1609_4::timeLeftTillGuardOver() const
{
ASSERT(useSCH);
simtime_t sTime = simTime();
if (sTime - nextChannelSwitch->getSendingTime() <= GUARD_INTERVAL_11P) {
return GUARD_INTERVAL_11P - (sTime - nextChannelSwitch->getSendingTime());
}
else
return 0;
}
/* returns the time left in this channel window */
simtime_t Mac1609_4::timeLeftInSlot() const
{
ASSERT(useSCH);
return nextChannelSwitch->getArrivalTime() - simTime();
}
/* Will change the Service Channel on which the mac layer is listening and sending */
void Mac1609_4::changeServiceChannel(Channel cN)
{
ASSERT(useSCH);
mySCH = static_cast<Channel>(cN);
if (mySCH != Channel::sch1 && mySCH != Channel::sch2 && mySCH != Channel::sch3 && mySCH != Channel::sch4) {
throw cRuntimeError("This Service Channel doesnt exit: %d", cN);
}
if (activeChannel == ChannelType::service) {
// change to new chan immediately if we are in a SCH slot,
// otherwise it will switch to the new SCH upon next channel switch
phy11p->changeListeningChannel(mySCH);
}
}
void Mac1609_4::setTxPower(double txPower_mW)
{
txPower = txPower_mW;
}
void Mac1609_4::setMCS(MCS mcs)
{
ASSERT2(mcs != MCS::undefined, "invalid MCS selected");
this->mcs = mcs;
}
void Mac1609_4::setCCAThreshold(double ccaThreshold_dBm)
{
phy11p->setCCAThreshold(ccaThreshold_dBm);
}
void Mac1609_4::handleBroadcast(Mac80211Pkt* macPkt, DeciderResult80211* res)
{
statsReceivedBroadcasts++;
unique_ptr<BaseFrame1609_4> wsm(check_and_cast<BaseFrame1609_4*>(macPkt->decapsulate()));
wsm->setControlInfo(new PhyToMacControlInfo(res));
sendUp(wsm.release());
}
void Mac1609_4::handleLowerMsg(cMessage* msg)
{
Mac80211Pkt* macPkt = check_and_cast<Mac80211Pkt*>(msg);
// pass information about received frame to the upper layers
DeciderResult80211* macRes = check_and_cast<DeciderResult80211*>(PhyToMacControlInfo::getDeciderResult(msg));
DeciderResult80211* res = new DeciderResult80211(*macRes);
long dest = macPkt->getDestAddr();
EV_TRACE << "Received frame name= " << macPkt->getName() << ", myState= src=" << macPkt->getSrcAddr() << " dst=" << macPkt->getDestAddr() << " myAddr=" << myMacAddr << std::endl;
if (dest == myMacAddr) {
if (auto* ack = dynamic_cast<Mac80211Ack*>(macPkt)) {
ASSERT(useAcks);
handleAck(ack);
delete res;
}
else {
unique_ptr<BaseFrame1609_4> wsm(check_and_cast<BaseFrame1609_4*>(macPkt->decapsulate()));
wsm->setControlInfo(new PhyToMacControlInfo(res));
handleUnicast(macPkt->getSrcAddr(), std::move(wsm));
}
}
else if (dest == LAddress::L2BROADCAST()) {
handleBroadcast(macPkt, res);
}
else {
EV_TRACE << "Packet not for me" << std::endl;
delete res;
}
delete macPkt;
if (rxStartIndication) {
// We have handled/processed the incoming packet
// Since we reached here, we were expecting an ack but we didnt get it, so retransmission should take place
phy11p->notifyMacAboutRxStart(false);
rxStartIndication = false;
handleRetransmit(lastAC);
}
}
int Mac1609_4::EDCA::queuePacket(t_access_category ac, BaseFrame1609_4* msg)
{
if (maxQueueSize && myQueues[ac].queue.size() >= maxQueueSize) {
delete msg;
return -1;
}
myQueues[ac].queue.push(msg);
return myQueues[ac].queue.size();
}
void Mac1609_4::EDCA::createQueue(int aifsn, int cwMin, int cwMax, t_access_category ac)
{
if (myQueues.find(ac) != myQueues.end()) {
throw cRuntimeError("You can only add one queue per Access Category per EDCA subsystem");
}
EDCAQueue newQueue(aifsn, cwMin, cwMax, ac);
myQueues[ac] = newQueue;
}
Mac1609_4::t_access_category Mac1609_4::mapUserPriority(int prio)
{
// Map user priority to access category, based on IEEE Std 802.11-2012, Table 9-1
switch (prio) {
case 1:
return AC_BK;
case 2:
return AC_BK;
case 0:
return AC_BE;
case 3:
return AC_BE;
case 4:
return AC_VI;
case 5:
return AC_VI;
case 6:
return AC_VO;
case 7:
return AC_VO;
default:
throw cRuntimeError("MacLayer received a packet with unknown priority");
break;
}
return AC_VO;
}
BaseFrame1609_4* Mac1609_4::EDCA::initiateTransmit(simtime_t lastIdle)
{
// iterate through the queues to return the packet we want to send
BaseFrame1609_4* pktToSend = nullptr;
simtime_t idleTime = simTime() - lastIdle;
EV_TRACE << "Initiating transmit at " << simTime() << ". I've been idle since " << idleTime << std::endl;
// As t_access_category is sorted by priority, we iterate back to front.
// This realizes the behavior documented in IEEE Std 802.11-2012 Section 9.2.4.2; that is, "data frames from the higher priority AC" win an internal collision.
// The phrase "EDCAF of higher UP" of IEEE Std 802.11-2012 Section 9.19.2.3 is assumed to be meaningless.
for (auto iter = myQueues.rbegin(); iter != myQueues.rend(); iter++) {
if (iter->second.queue.size() != 0 && !iter->second.waitForAck) {
if (idleTime >= iter->second.aifsn * SLOTLENGTH_11P + SIFS_11P && iter->second.txOP == true) {
EV_TRACE << "Queue " << iter->first << " is ready to send!" << std::endl;
iter->second.txOP = false;
// this queue is ready to send
if (pktToSend == nullptr) {
pktToSend = iter->second.queue.front();
}
else {
// there was already another packet ready. we have to go increase cw and go into backoff. It's called internal contention and its wonderful
statsNumInternalContention++;
iter->second.cwCur = std::min(iter->second.cwMax, (iter->second.cwCur + 1) * 2 - 1);
iter->second.currentBackoff = owner->intuniform(0, iter->second.cwCur);
EV_TRACE << "Internal contention for queue " << iter->first << " : " << iter->second.currentBackoff << ". Increase cwCur to " << iter->second.cwCur << std::endl;
}
}
}
}
if (pktToSend == nullptr) {
throw cRuntimeError("No packet was ready");
}
return pktToSend;
}
simtime_t Mac1609_4::EDCA::startContent(simtime_t idleSince, bool guardActive)
{
EV_TRACE << "Restarting contention." << std::endl;
simtime_t nextEvent = -1;
simtime_t idleTime = SimTime().setRaw(std::max((int64_t) 0, (simTime() - idleSince).raw()));
;
lastStart = idleSince;
EV_TRACE << "Channel is already idle for:" << idleTime << " since " << idleSince << std::endl;
// this returns the nearest possible event in this EDCA subsystem after a busy channel
for (auto&& p : myQueues) {
auto& accessCategory = p.first;
auto& edcaQueue = p.second;
if (edcaQueue.queue.size() != 0 && !edcaQueue.waitForAck) {
/* 1609_4 says that when attempting to send (backoff == 0) when guard is active, a random backoff is invoked */
if (guardActive == true && edcaQueue.currentBackoff == 0) {
// cw is not increased
edcaQueue.currentBackoff = owner->intuniform(0, edcaQueue.cwCur);
statsNumBackoff++;
}
simtime_t DIFS = edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P;
// the next possible time to send can be in the past if the channel was idle for a long time, meaning we COULD have sent earlier if we had a packet
simtime_t possibleNextEvent = DIFS + edcaQueue.currentBackoff * SLOTLENGTH_11P;
EV_TRACE << "Waiting Time for Queue " << accessCategory << ":" << possibleNextEvent << "=" << edcaQueue.aifsn << " * " << SLOTLENGTH_11P << " + " << SIFS_11P << "+" << edcaQueue.currentBackoff << "*" << SLOTLENGTH_11P << "; Idle time: " << idleTime << std::endl;
if (idleTime > possibleNextEvent) {
EV_TRACE << "Could have already send if we had it earlier" << std::endl;
// we could have already sent. round up to next boundary
simtime_t base = idleSince + DIFS;
possibleNextEvent = simTime() - simtime_t().setRaw((simTime() - base).raw() % SLOTLENGTH_11P.raw()) + SLOTLENGTH_11P;
}
else {
// we are gonna send in the future
EV_TRACE << "Sending in the future" << std::endl;
possibleNextEvent = idleSince + possibleNextEvent;
}
nextEvent == -1 ? nextEvent = possibleNextEvent : nextEvent = std::min(nextEvent, possibleNextEvent);
}
}
return nextEvent;
}
void Mac1609_4::EDCA::stopContent(bool allowBackoff, bool generateTxOp)
{
// update all Queues
EV_TRACE << "Stopping Contention at " << simTime().raw() << std::endl;
simtime_t passedTime = simTime() - lastStart;
EV_TRACE << "Channel was idle for " << passedTime << std::endl;
lastStart = -1; // indicate that there was no last start
for (auto&& p : myQueues) {
auto& accessCategory = p.first;
auto& edcaQueue = p.second;
if ((edcaQueue.currentBackoff != 0 || edcaQueue.queue.size() != 0) && !edcaQueue.waitForAck) {
// check how many slots we already waited until the chan became busy
int64_t oldBackoff = edcaQueue.currentBackoff;
std::string info;
if (passedTime < edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P) {
// we didnt even make it one DIFS :(
info.append(" No DIFS");
}
else {
// decrease the backoff by one because we made it longer than one DIFS
edcaQueue.currentBackoff -= 1;
// check how many slots we waited after the first DIFS
int64_t passedSlots = (int64_t)((passedTime - SimTime(edcaQueue.aifsn * SLOTLENGTH_11P + SIFS_11P)) / SLOTLENGTH_11P);
EV_TRACE << "Passed slots after DIFS: " << passedSlots << std::endl;
if (edcaQueue.queue.size() == 0) {
// this can be below 0 because of post transmit backoff -> backoff on empty queues will not generate macevents,
// we dont want to generate a txOP for empty queues
edcaQueue.currentBackoff -= std::min(edcaQueue.currentBackoff, passedSlots);
info.append(" PostCommit Over");
}
else {
edcaQueue.currentBackoff -= passedSlots;
if (edcaQueue.currentBackoff <= -1) {
if (generateTxOp) {
edcaQueue.txOP = true;
info.append(" TXOP");
}
// else: this packet couldnt be sent because there was too little time. we could have generated a txop, but the channel switched
edcaQueue.currentBackoff = 0;
}
}
}
EV_TRACE << "Updating backoff for Queue " << accessCategory << ": " << oldBackoff << " -> " << edcaQueue.currentBackoff << info << std::endl;
}
}
}
void Mac1609_4::EDCA::backoff(t_access_category ac)
{
myQueues[ac].currentBackoff = owner->intuniform(0, myQueues[ac].cwCur);
statsSlotsBackoff += myQueues[ac].currentBackoff;
statsNumBackoff++;
EV_TRACE << "Going into Backoff because channel was busy when new packet arrived from upperLayer" << std::endl;
}
void Mac1609_4::EDCA::postTransmit(t_access_category ac, BaseFrame1609_4* wsm, bool useAcks)
{
bool holBlocking = (wsm->getRecipientAddress() != LAddress::L2BROADCAST()) && useAcks;
if (holBlocking) {
// mac->waitUntilAckRXorTimeout = true; // set in handleselfmsg()
// Head of line blocking, wait until ack timeout
myQueues[ac].waitForAck = true;
myQueues[ac].waitOnUnicastID = wsm->getTreeId();
((Mac1609_4*) owner)->phy11p->notifyMacAboutRxStart(true);
}
else {
myQueues[ac].waitForAck = false;
delete myQueues[ac].queue.front();
myQueues[ac].queue.pop();
myQueues[ac].cwCur = myQueues[ac].cwMin;
// post transmit backoff
myQueues[ac].currentBackoff = owner->intuniform(0, myQueues[ac].cwCur);
statsSlotsBackoff += myQueues[ac].currentBackoff;
statsNumBackoff++;
EV_TRACE << "Queue " << ac << " will go into post-transmit backoff for " << myQueues[ac].currentBackoff << " slots" << std::endl;
}
}
Mac1609_4::EDCA::EDCA(cSimpleModule* owner, ChannelType channelType, int maxQueueLength)
: HasLogProxy(owner)
, owner(owner)
, maxQueueSize(maxQueueLength)
, channelType(channelType)
, statsNumInternalContention(0)
, statsNumBackoff(0)
, statsSlotsBackoff(0)
{
}
Mac1609_4::EDCA::~EDCA()
{
for (auto& q : myQueues) {
auto& ackTimeout = q.second.ackTimeOut;
if (ackTimeout) {
owner->cancelAndDelete(ackTimeout);
ackTimeout = nullptr;
}
}
}
void Mac1609_4::EDCA::revokeTxOPs()
{
for (auto&& p : myQueues) {
auto& edcaQueue = p.second;
if (edcaQueue.txOP == true) {
edcaQueue.txOP = false;
edcaQueue.currentBackoff = 0;
}
}
}
void Mac1609_4::channelBusySelf(bool generateTxOp)
{
// the channel turned busy because we're sending. we don't want our queues to go into backoff
// internal contention is already handled in initiateTransmission
if (!idleChannel) return;
idleChannel = false;
EV_TRACE << "Channel turned busy: Switch or Self-Send" << std::endl;
lastBusy = simTime();
// channel turned busy
if (nextMacEvent->isScheduled() == true) {
cancelEvent(nextMacEvent);
}
else {
// the edca subsystem was not doing anything anyway.
}
myEDCA[activeChannel]->stopContent(false, generateTxOp);
emit(sigChannelBusy, true);
}
void Mac1609_4::channelBusy()
{
if (!idleChannel) return;
// the channel turned busy because someone else is sending
idleChannel = false;
EV_TRACE << "Channel turned busy: External sender" << std::endl;
lastBusy = simTime();
// channel turned busy
if (nextMacEvent->isScheduled() == true) {
cancelEvent(nextMacEvent);
}
else {
// the edca subsystem was not doing anything anyway.
}
myEDCA[activeChannel]->stopContent(true, false);
emit(sigChannelBusy, true);
}
void Mac1609_4::channelIdle(bool afterSwitch)
{
EV_TRACE << "Channel turned idle: Switch: " << afterSwitch << std::endl;
if (waitUntilAckRXorTimeout) {
return;
}
if (nextMacEvent->isScheduled() == true) {
// this rare case can happen when another node's time has such a big offset that the node sent a packet although we already changed the channel
// the workaround is not trivial and requires a lot of changes to the phy and decider
return;
// throw cRuntimeError("channel turned idle but contention timer was scheduled!");
}
idleChannel = true;
simtime_t delay = 0;
// account for 1609.4 guards
if (afterSwitch) {
// delay = GUARD_INTERVAL_11P;
}
if (useSCH) {
delay += timeLeftTillGuardOver();
}
// channel turned idle! lets start contention!
lastIdle = delay + simTime();
statsTotalBusyTime += simTime() - lastBusy;
// get next Event from current EDCA subsystem
simtime_t nextEvent = myEDCA[activeChannel]->startContent(lastIdle, guardActive());
if (nextEvent != -1) {
if ((!useSCH) || (nextEvent < nextChannelSwitch->getArrivalTime())) {
scheduleAt(nextEvent, nextMacEvent);
EV_TRACE << "next Event is at " << nextMacEvent->getArrivalTime().raw() << std::endl;
}
else {
EV_TRACE << "Too little time in this interval. will not schedule macEvent" << std::endl;
statsNumTooLittleTime++;
myEDCA[activeChannel]->revokeTxOPs();
}
}
else {
EV_TRACE << "I don't have any new events in this EDCA sub system" << std::endl;
}
emit(sigChannelBusy, false);
}
void Mac1609_4::setParametersForBitrate(uint64_t bitrate)
{
mcs = getMCS(bitrate, BANDWIDTH_11P);
if (mcs == MCS::undefined) {
throw cRuntimeError("Chosen Bitrate is not valid for 802.11p: Valid rates are: 3Mbps, 4.5Mbps, 6Mbps, 9Mbps, 12Mbps, 18Mbps, 24Mbps and 27Mbps. Please adjust your omnetpp.ini file accordingly.");
}
}
bool Mac1609_4::isChannelSwitchingActive()
{
return useSCH;
}
simtime_t Mac1609_4::getSwitchingInterval()
{
return SWITCHING_INTERVAL_11P;
}
bool Mac1609_4::isCurrentChannelCCH()
{
return (activeChannel == ChannelType::control);
}
// Unicast
void Mac1609_4::sendAck(LAddress::L2Type recpAddress, unsigned long wsmId)
{
ASSERT(useAcks);
// 802.11-2012 9.3.2.8
// send an ACK after SIFS without regard of busy/ idle state of channel
ignoreChannelState = true;
channelBusySelf(true);
// send the packet
auto* mac = new Mac80211Ack("ACK");
mac->setDestAddr(recpAddress);
mac->setSrcAddr(myMacAddr);
mac->setMessageId(wsmId);
mac->setBitLength(ackLength);
simtime_t sendingDuration = RADIODELAY_11P + phy11p->getFrameDuration(mac->getBitLength(), mcs);
EV_TRACE << "Ack sending duration will be " << sendingDuration << std::endl;
// TODO: check ack procedure when channel switching is allowed
// double freq = (activeChannel == ChannelType::control) ? IEEE80211ChannelFrequencies.at(Channel::cch) : IEEE80211ChannelFrequencies.at(mySCH);
double freq = IEEE80211ChannelFrequencies.at(Channel::cch);
EV_TRACE << "Sending an ack. Frequency " << freq << " at time : " << simTime() + SIFS_11P << std::endl;
sendFrame(mac, SIFS_11P, Channel::cch, mcs, txPower);
scheduleAt(simTime() + SIFS_11P, stopIgnoreChannelStateMsg);
}
void Mac1609_4::handleUnicast(LAddress::L2Type srcAddr, unique_ptr<BaseFrame1609_4> wsm)
{
if (useAcks) {
sendAck(srcAddr, wsm->getTreeId());
}
if (handledUnicastToApp.find(wsm->getTreeId()) == handledUnicastToApp.end()) {
handledUnicastToApp.insert(wsm->getTreeId());
EV_TRACE << "Received a data packet addressed to me." << std::endl;
statsReceivedPackets++;
sendUp(wsm.release());
}
}
void Mac1609_4::handleAck(const Mac80211Ack* ack)
{
ASSERT2(rxStartIndication, "Not expecting ack");
phy11p->notifyMacAboutRxStart(false);
rxStartIndication = false;
ChannelType chan = ChannelType::control;
bool queueUnblocked = false;
for (auto&& p : myEDCA[chan]->myQueues) {
auto& accessCategory = p.first;
auto& edcaQueue = p.second;
if (edcaQueue.queue.size() > 0 && edcaQueue.waitForAck && (edcaQueue.waitOnUnicastID == ack->getMessageId())) {
BaseFrame1609_4* wsm = edcaQueue.queue.front();
edcaQueue.queue.pop();
delete wsm;
myEDCA[chan]->myQueues[accessCategory].cwCur = myEDCA[chan]->myQueues[accessCategory].cwMin;
myEDCA[chan]->backoff(accessCategory);
edcaQueue.ssrc = 0;
edcaQueue.slrc = 0;
edcaQueue.waitForAck = false;
edcaQueue.waitOnUnicastID = -1;
if (myEDCA[chan]->myQueues[accessCategory].ackTimeOut->isScheduled()) {
cancelEvent(myEDCA[chan]->myQueues[accessCategory].ackTimeOut);
}
queueUnblocked = true;
}
}
if (!queueUnblocked) {
throw cRuntimeError("Could not find WSM in EDCA queues with WSM ID received in ACK");
}
else {
waitUntilAckRXorTimeout = false;
}
}
void Mac1609_4::handleAckTimeOut(AckTimeOutMessage* ackTimeOutMsg)
{
if (rxStartIndication) {
// Rx is already in process. Wait for it to complete.
// In case it is not an ack, we will retransmit
// This assigning might be redundant as it was set already in handleSelfMsg but no harm in reassigning here.
lastAC = (t_access_category)(ackTimeOutMsg->getKind());
return;
}
// We did not start receiving any packet.
// stop receiving notification for rx start as we will retransmit
phy11p->notifyMacAboutRxStart(false);
// back off and try retransmission again
handleRetransmit((t_access_category)(ackTimeOutMsg->getKind()));
// Phy was requested not to send channel idle status on TX_OVER
// So request the channel status now. For the case when we receive ACK, decider updates channel status itself after ACK RX
phy11p->requestChannelStatusIfIdle();
}
void Mac1609_4::handleRetransmit(t_access_category ac)
{
// cancel the acktime out
if (myEDCA[ChannelType::control]->myQueues[ac].ackTimeOut->isScheduled()) {
// This case is possible if we received PHY_RX_END_WITH_SUCCESS or FAILURE even before ack timeout
cancelEvent(myEDCA[ChannelType::control]->myQueues[ac].ackTimeOut);
}
if (myEDCA[ChannelType::control]->myQueues[ac].queue.size() == 0) {
throw cRuntimeError("Trying retransmission on empty queue...");
}
BaseFrame1609_4* appPkt = myEDCA[ChannelType::control]->myQueues[ac].queue.front();
bool contend = false;
bool retriesExceeded = false;
// page 879 of IEEE 802.11-2012
if (appPkt->getBitLength() <= dot11RTSThreshold) {
myEDCA[ChannelType::control]->myQueues[ac].ssrc++;
if (myEDCA[ChannelType::control]->myQueues[ac].ssrc <= dot11ShortRetryLimit) {
retriesExceeded = false;
}
else {
retriesExceeded = true;
}
}
else {
myEDCA[ChannelType::control]->myQueues[ac].slrc++;
if (myEDCA[ChannelType::control]->myQueues[ac].slrc <= dot11LongRetryLimit) {
retriesExceeded = false;
}
else {
retriesExceeded = true;
}
}
if (!retriesExceeded) {
// try again!
myEDCA[ChannelType::control]->myQueues[ac].cwCur = std::min(myEDCA[ChannelType::control]->myQueues[ac].cwMax, (myEDCA[ChannelType::control]->myQueues[ac].cwCur * 2) + 1);
myEDCA[ChannelType::control]->backoff(ac);
contend = true;
// no need to reset wait on id here as we are still retransmitting same packet
myEDCA[ChannelType::control]->myQueues[ac].waitForAck = false;
}
else {
// enough tries!
myEDCA[ChannelType::control]->myQueues[ac].queue.pop();
if (myEDCA[ChannelType::control]->myQueues[ac].queue.size() > 0) {
// start contention only if there are more packets in the queue
contend = true;
}
delete appPkt;
myEDCA[ChannelType::control]->myQueues[ac].cwCur = myEDCA[ChannelType::control]->myQueues[ac].cwMin;
myEDCA[ChannelType::control]->backoff(ac);
myEDCA[ChannelType::control]->myQueues[ac].waitForAck = false;
myEDCA[ChannelType::control]->myQueues[ac].waitOnUnicastID = -1;
myEDCA[ChannelType::control]->myQueues[ac].ssrc = 0;
myEDCA[ChannelType::control]->myQueues[ac].slrc = 0;
}
waitUntilAckRXorTimeout = false;
if (contend && idleChannel && !ignoreChannelState) {
// reevaluate times -- if channel is not idle, then contention would start automatically
cancelEvent(nextMacEvent);
simtime_t nextEvent = myEDCA[ChannelType::control]->startContent(lastIdle, guardActive());
scheduleAt(nextEvent, nextMacEvent);
}
}
Mac1609_4::EDCA::EDCAQueue::EDCAQueue(int aifsn, int cwMin, int cwMax, t_access_category ac)
: aifsn(aifsn)
, cwMin(cwMin)
, cwMax(cwMax)
, cwCur(cwMin)
, currentBackoff(0)
, txOP(false)
, ssrc(0)
, slrc(0)
, waitForAck(false)
, waitOnUnicastID(-1)
, ackTimeOut(new AckTimeOutMessage("AckTimeOut"))
{
ackTimeOut->setKind(ac);
}
Mac1609_4::EDCA::EDCAQueue::~EDCAQueue()
{
while (!queue.empty()) {
delete queue.front();
queue.pop();
}
// ackTimeOut needs to be deleted in EDCA
}
| 43,487 | 36.392949 | 274 | cc |
null | AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac1609_4.h | //
// Copyright (C) 2012 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <queue>
#include <memory>
#include <stdint.h>
#include "veins/veins.h"
#include "veins/base/modules/BaseLayer.h"
#include "veins/modules/phy/PhyLayer80211p.h"
#include "veins/modules/mac/ieee80211p/DemoBaseApplLayerToMac1609_4Interface.h"
#include "veins/modules/utility/Consts80211p.h"
#include "veins/modules/utility/MacToPhyControlInfo11p.h"
#include "veins/base/utils/FindModule.h"
#include "veins/modules/messages/Mac80211Pkt_m.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
#include "veins/modules/messages/AckTimeOutMessage_m.h"
#include "veins/modules/messages/Mac80211Ack_m.h"
#include "veins/base/modules/BaseMacLayer.h"
#include "veins/modules/utility/ConstsPhy.h"
#include "veins/modules/utility/HasLogProxy.h"
namespace veins {
/**
* @brief
* Manages timeslots for CCH and SCH listening and sending.
*
* @author David Eckhoff : rewrote complete model
* @author Christoph Sommer : features and bug fixes
* @author Michele Segata : features and bug fixes
* @author Stefan Joerer : features and bug fixes
* @author Gurjashan Pannu: features (unicast model)
* @author Christopher Saloman: initial version
*
* @ingroup macLayer
*
* @see DemoBaseApplLayer
* @see Mac1609_4
* @see PhyLayer80211p
* @see Decider80211p
*/
class DeciderResult80211;
class VEINS_API Mac1609_4 : public BaseMacLayer, public DemoBaseApplLayerToMac1609_4Interface {
public:
// tell to anybody which is interested when the channel turns busy or idle
static const simsignal_t sigChannelBusy;
// tell to anybody which is interested when a collision occurred
static const simsignal_t sigCollision;
// Access categories in increasing order of priority (see IEEE Std 802.11-2012, Table 9-1)
enum t_access_category {
AC_BK = 0,
AC_BE = 1,
AC_VI = 2,
AC_VO = 3
};
class VEINS_API EDCA : HasLogProxy {
public:
class VEINS_API EDCAQueue {
public:
std::queue<BaseFrame1609_4*> queue;
int aifsn; // number of aifs slots for this queue
int cwMin; // minimum contention window
int cwMax; // maximum contention size
int cwCur; // current contention window
int64_t currentBackoff; // current Backoff value for this queue
bool txOP;
int ssrc; // station short retry count
int slrc; // station long retry count
bool waitForAck; // true if the queue is waiting for an acknowledgment for unicast
unsigned long waitOnUnicastID; // unique id of unicast on which station is waiting
AckTimeOutMessage* ackTimeOut; // timer for retransmission on receiving no ACK
EDCAQueue()
{
}
EDCAQueue(int aifsn, int cwMin, int cwMax, t_access_category ac);
~EDCAQueue();
};
EDCA(cSimpleModule* owner, ChannelType channelType, int maxQueueLength = 0);
~EDCA();
void createQueue(int aifsn, int cwMin, int cwMax, t_access_category);
int queuePacket(t_access_category AC, BaseFrame1609_4* cmsg);
void backoff(t_access_category ac);
simtime_t startContent(simtime_t idleSince, bool guardActive);
void stopContent(bool allowBackoff, bool generateTxOp);
void postTransmit(t_access_category, BaseFrame1609_4* wsm, bool useAcks);
void revokeTxOPs();
/** @brief return the next packet to send, send all lower Queues into backoff */
BaseFrame1609_4* initiateTransmit(simtime_t idleSince);
public:
cSimpleModule* owner;
std::map<t_access_category, EDCAQueue> myQueues;
uint32_t maxQueueSize;
simtime_t lastStart; // when we started the last contention;
ChannelType channelType;
/** @brief Stats */
long statsNumInternalContention;
long statsNumBackoff;
long statsSlotsBackoff;
/** @brief Id for debug messages */
std::string myId;
};
public:
Mac1609_4()
: nextChannelSwitch(nullptr)
, nextMacEvent(nullptr)
{
}
~Mac1609_4() override;
/**
* @brief return true if alternate access is enabled
*/
bool isChannelSwitchingActive() override;
simtime_t getSwitchingInterval() override;
bool isCurrentChannelCCH() override;
void changeServiceChannel(Channel channelNumber) override;
/**
* @brief Change the default tx power the NIC card is using
*
* @param txPower_mW the tx power to be set in mW
*/
void setTxPower(double txPower_mW);
/**
* @brief Change the default MCS the NIC card is using
*
* @param mcs the default modulation and coding scheme
* to use
*/
void setMCS(MCS mcs);
/**
* @brief Change the phy layer carrier sense threshold.
*
* @param ccaThreshold_dBm the cca threshold in dBm
*/
void setCCAThreshold(double ccaThreshold_dBm);
protected:
/** @brief States of the channel selecting operation.*/
protected:
/** @brief Initialization of the module and some variables.*/
void initialize(int) override;
/** @brief Delete all dynamically allocated objects of the module.*/
void finish() override;
/** @brief Handle messages from lower layer.*/
void handleLowerMsg(cMessage*) override;
/** @brief Handle messages from upper layer.*/
void handleUpperMsg(cMessage*) override;
/** @brief Handle control messages from upper layer.*/
void handleUpperControl(cMessage* msg) override;
/** @brief Handle self messages such as timers.*/
void handleSelfMsg(cMessage*) override;
/** @brief Handle control messages from lower layer.*/
void handleLowerControl(cMessage* msg) override;
/** @brief Handle received broadcast */
virtual void handleBroadcast(Mac80211Pkt* macPkt, DeciderResult80211* res);
/** @brief Set a state for the channel selecting operation.*/
void setActiveChannel(ChannelType state);
void sendFrame(Mac80211Pkt* frame, omnetpp::simtime_t delay, Channel channelNr, MCS mcs, double txPower_mW);
simtime_t timeLeftInSlot() const;
simtime_t timeLeftTillGuardOver() const;
bool guardActive() const;
void attachControlInfo(Mac80211Pkt* mac, Channel channelNr, MCS mcs, double txPower_mW);
/** @brief maps a application layer priority (up) to an EDCA access category. */
t_access_category mapUserPriority(int prio);
void channelBusy();
void channelBusySelf(bool generateTxOp);
void channelIdle(bool afterSwitch = false);
void setParametersForBitrate(uint64_t bitrate);
void sendAck(LAddress::L2Type recpAddress, unsigned long wsmId);
void handleUnicast(LAddress::L2Type srcAddr, std::unique_ptr<BaseFrame1609_4> wsm);
void handleAck(const Mac80211Ack* ack);
void handleAckTimeOut(AckTimeOutMessage* ackTimeOutMsg);
void handleRetransmit(t_access_category ac);
const LAddress::L2Type& getMACAddress() override
{
ASSERT(myMacAddr != LAddress::L2NULL());
return BaseMacLayer::getMACAddress();
}
protected:
/** @brief Self message to indicate that the current channel shall be switched.*/
cMessage* nextChannelSwitch;
/** @brief Self message to wake up at next MacEvent */
cMessage* nextMacEvent;
/** @brief Last time the channel went idle */
simtime_t lastIdle;
simtime_t lastBusy;
/** @brief Current state of the channel selecting operation.*/
ChannelType activeChannel;
/** @brief access category of last sent packet */
t_access_category lastAC;
/** @brief pointer to last sent packet */
BaseFrame1609_4* lastWSM;
/** @brief pointer to last sent mac frame */
std::unique_ptr<Mac80211Pkt> lastMac;
int headerLength;
bool useSCH;
Channel mySCH;
std::map<ChannelType, std::unique_ptr<EDCA>> myEDCA;
bool idleChannel;
/** @brief stats */
long statsReceivedPackets;
long statsReceivedBroadcasts;
long statsSentPackets;
long statsSentAcks;
long statsTXRXLostPackets;
long statsSNIRLostPackets;
long statsDroppedPackets;
long statsNumTooLittleTime;
long statsNumInternalContention;
long statsNumBackoff;
long statsSlotsBackoff;
simtime_t statsTotalBusyTime;
/** @brief The power (in mW) to transmit with.*/
double txPower;
MCS mcs; ///< Modulation and coding scheme to use unless explicitly specified.
/** @brief Id for debug messages */
std::string myId;
bool useAcks;
double ackErrorRate;
int dot11RTSThreshold;
int dot11ShortRetryLimit;
int dot11LongRetryLimit;
int ackLength;
// indicates rx start within the period of ACK timeout
bool rxStartIndication;
// An ack is sent after SIFS irrespective of the channel state
cMessage* stopIgnoreChannelStateMsg;
bool ignoreChannelState;
// Dont start contention immediately after finishing unicast TX. Wait until ack timeout/ ack Rx
bool waitUntilAckRXorTimeout;
std::set<unsigned long> handledUnicastToApp;
Mac80211pToPhy11pInterface* phy11p;
};
} // namespace veins
| 10,064 | 30.851266 | 112 | h |
null | AICP-main/veins/src/veins/modules/mac/ieee80211p/Mac80211pToPhy11pInterface.h | //
// Copyright (C) 2011 David Eckhoff <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/base/phyLayer/MacToPhyInterface.h"
#include "veins/modules/utility/ConstsPhy.h"
#include "veins/modules/utility/Consts80211p.h"
namespace veins {
/**
* @brief
* Interface of PhyLayer80211p exposed to Mac1609_4.
*
* @author Christopher Saloman
* @author David Eckhoff
*
* @ingroup phyLayer
*/
class VEINS_API Mac80211pToPhy11pInterface {
public:
enum BasePhyMessageKinds {
CHANNEL_IDLE,
CHANNEL_BUSY,
};
virtual ~Mac80211pToPhy11pInterface() = default;
virtual void changeListeningChannel(Channel channel) = 0;
virtual void setCCAThreshold(double ccaThreshold_dBm) = 0;
virtual void notifyMacAboutRxStart(bool enable) = 0;
virtual void requestChannelStatusIfIdle() = 0;
virtual simtime_t getFrameDuration(int payloadLengthBits, MCS mcs) const = 0;
};
} // namespace veins
| 1,757 | 29.842105 | 81 | h |
null | AICP-main/veins/src/veins/modules/messages/AckTimeOutMessage_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AckTimeOutMessage.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "AckTimeOutMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(AckTimeOutMessage)
AckTimeOutMessage::AckTimeOutMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind)
{
this->wsmId = -1;
this->ac = -1;
}
AckTimeOutMessage::AckTimeOutMessage(const AckTimeOutMessage& other) : ::omnetpp::cMessage(other)
{
copy(other);
}
AckTimeOutMessage::~AckTimeOutMessage()
{
}
AckTimeOutMessage& AckTimeOutMessage::operator=(const AckTimeOutMessage& other)
{
if (this==&other) return *this;
::omnetpp::cMessage::operator=(other);
copy(other);
return *this;
}
void AckTimeOutMessage::copy(const AckTimeOutMessage& other)
{
this->wsmId = other.wsmId;
this->ac = other.ac;
}
void AckTimeOutMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cMessage::parsimPack(b);
doParsimPacking(b,this->wsmId);
doParsimPacking(b,this->ac);
}
void AckTimeOutMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cMessage::parsimUnpack(b);
doParsimUnpacking(b,this->wsmId);
doParsimUnpacking(b,this->ac);
}
unsigned long AckTimeOutMessage::getWsmId() const
{
return this->wsmId;
}
void AckTimeOutMessage::setWsmId(unsigned long wsmId)
{
this->wsmId = wsmId;
}
int AckTimeOutMessage::getAc() const
{
return this->ac;
}
void AckTimeOutMessage::setAc(int ac)
{
this->ac = ac;
}
class AckTimeOutMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
AckTimeOutMessageDescriptor();
virtual ~AckTimeOutMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(AckTimeOutMessageDescriptor)
AckTimeOutMessageDescriptor::AckTimeOutMessageDescriptor() : omnetpp::cClassDescriptor("veins::AckTimeOutMessage", "omnetpp::cMessage")
{
propertynames = nullptr;
}
AckTimeOutMessageDescriptor::~AckTimeOutMessageDescriptor()
{
delete[] propertynames;
}
bool AckTimeOutMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<AckTimeOutMessage *>(obj)!=nullptr;
}
const char **AckTimeOutMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *AckTimeOutMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int AckTimeOutMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount() : 2;
}
unsigned int AckTimeOutMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *AckTimeOutMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"wsmId",
"ac",
};
return (field>=0 && field<2) ? fieldNames[field] : nullptr;
}
int AckTimeOutMessageDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='w' && strcmp(fieldName, "wsmId")==0) return base+0;
if (fieldName[0]=='a' && strcmp(fieldName, "ac")==0) return base+1;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *AckTimeOutMessageDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"unsigned long",
"int",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr;
}
const char **AckTimeOutMessageDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *AckTimeOutMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int AckTimeOutMessageDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *AckTimeOutMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string AckTimeOutMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp;
switch (field) {
case 0: return ulong2string(pp->getWsmId());
case 1: return long2string(pp->getAc());
default: return "";
}
}
bool AckTimeOutMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp;
switch (field) {
case 0: pp->setWsmId(string2ulong(value)); return true;
case 1: pp->setAc(string2long(value)); return true;
default: return false;
}
}
const char *AckTimeOutMessageDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *AckTimeOutMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
AckTimeOutMessage *pp = (AckTimeOutMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 15,189 | 30.449275 | 135 | cc |
null | AICP-main/veins/src/veins/modules/messages/AckTimeOutMessage_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AckTimeOutMessage.msg.
//
#ifndef __VEINS_ACKTIMEOUTMESSAGE_M_H
#define __VEINS_ACKTIMEOUTMESSAGE_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/AckTimeOutMessage.msg:25</tt> by nedtool.
* <pre>
* message AckTimeOutMessage
* {
* // The corresponding WSM's tree id
* unsigned long wsmId = -1;
* // Access category on which the AckTimer is set
* int ac = -1;
* }
* </pre>
*/
class VEINS_API AckTimeOutMessage : public ::omnetpp::cMessage
{
protected:
unsigned long wsmId;
int ac;
private:
void copy(const AckTimeOutMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const AckTimeOutMessage&);
public:
AckTimeOutMessage(const char *name=nullptr, short kind=0);
AckTimeOutMessage(const AckTimeOutMessage& other);
virtual ~AckTimeOutMessage();
AckTimeOutMessage& operator=(const AckTimeOutMessage& other);
virtual AckTimeOutMessage *dup() const override {return new AckTimeOutMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual unsigned long getWsmId() const;
virtual void setWsmId(unsigned long wsmId);
virtual int getAc() const;
virtual void setAc(int ac);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const AckTimeOutMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, AckTimeOutMessage& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_ACKTIMEOUTMESSAGE_M_H
| 2,303 | 27.444444 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/AirFrame11p_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AirFrame11p.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "AirFrame11p_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(AirFrame11p)
AirFrame11p::AirFrame11p(const char *name, short kind) : ::veins::AirFrame(name,kind)
{
this->underMinPowerLevel = false;
this->wasTransmitting = false;
}
AirFrame11p::AirFrame11p(const AirFrame11p& other) : ::veins::AirFrame(other)
{
copy(other);
}
AirFrame11p::~AirFrame11p()
{
}
AirFrame11p& AirFrame11p::operator=(const AirFrame11p& other)
{
if (this==&other) return *this;
::veins::AirFrame::operator=(other);
copy(other);
return *this;
}
void AirFrame11p::copy(const AirFrame11p& other)
{
this->underMinPowerLevel = other.underMinPowerLevel;
this->wasTransmitting = other.wasTransmitting;
}
void AirFrame11p::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::AirFrame::parsimPack(b);
doParsimPacking(b,this->underMinPowerLevel);
doParsimPacking(b,this->wasTransmitting);
}
void AirFrame11p::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::AirFrame::parsimUnpack(b);
doParsimUnpacking(b,this->underMinPowerLevel);
doParsimUnpacking(b,this->wasTransmitting);
}
bool AirFrame11p::getUnderMinPowerLevel() const
{
return this->underMinPowerLevel;
}
void AirFrame11p::setUnderMinPowerLevel(bool underMinPowerLevel)
{
this->underMinPowerLevel = underMinPowerLevel;
}
bool AirFrame11p::getWasTransmitting() const
{
return this->wasTransmitting;
}
void AirFrame11p::setWasTransmitting(bool wasTransmitting)
{
this->wasTransmitting = wasTransmitting;
}
class AirFrame11pDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
AirFrame11pDescriptor();
virtual ~AirFrame11pDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(AirFrame11pDescriptor)
AirFrame11pDescriptor::AirFrame11pDescriptor() : omnetpp::cClassDescriptor("veins::AirFrame11p", "veins::AirFrame")
{
propertynames = nullptr;
}
AirFrame11pDescriptor::~AirFrame11pDescriptor()
{
delete[] propertynames;
}
bool AirFrame11pDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<AirFrame11p *>(obj)!=nullptr;
}
const char **AirFrame11pDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *AirFrame11pDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int AirFrame11pDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount() : 2;
}
unsigned int AirFrame11pDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *AirFrame11pDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"underMinPowerLevel",
"wasTransmitting",
};
return (field>=0 && field<2) ? fieldNames[field] : nullptr;
}
int AirFrame11pDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='u' && strcmp(fieldName, "underMinPowerLevel")==0) return base+0;
if (fieldName[0]=='w' && strcmp(fieldName, "wasTransmitting")==0) return base+1;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *AirFrame11pDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"bool",
"bool",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr;
}
const char **AirFrame11pDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *AirFrame11pDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int AirFrame11pDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
AirFrame11p *pp = (AirFrame11p *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *AirFrame11pDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
AirFrame11p *pp = (AirFrame11p *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string AirFrame11pDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
AirFrame11p *pp = (AirFrame11p *)object; (void)pp;
switch (field) {
case 0: return bool2string(pp->getUnderMinPowerLevel());
case 1: return bool2string(pp->getWasTransmitting());
default: return "";
}
}
bool AirFrame11pDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
AirFrame11p *pp = (AirFrame11p *)object; (void)pp;
switch (field) {
case 0: pp->setUnderMinPowerLevel(string2bool(value)); return true;
case 1: pp->setWasTransmitting(string2bool(value)); return true;
default: return false;
}
}
const char *AirFrame11pDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *AirFrame11pDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
AirFrame11p *pp = (AirFrame11p *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 15,205 | 30.482402 | 128 | cc |
null | AICP-main/veins/src/veins/modules/messages/AirFrame11p_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/AirFrame11p.msg.
//
#ifndef __VEINS_AIRFRAME11P_M_H
#define __VEINS_AIRFRAME11P_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/messages/AirFrame_m.h"
using veins::AirFrame;
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/AirFrame11p.msg:35</tt> by nedtool.
* <pre>
* //
* // Extension of base AirFrame message to have the underMinPowerLevel field
* //
* message AirFrame11p extends AirFrame
* {
* bool underMinPowerLevel = false;
* bool wasTransmitting = false;
* }
* </pre>
*/
class VEINS_API AirFrame11p : public ::veins::AirFrame
{
protected:
bool underMinPowerLevel;
bool wasTransmitting;
private:
void copy(const AirFrame11p& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const AirFrame11p&);
public:
AirFrame11p(const char *name=nullptr, short kind=0);
AirFrame11p(const AirFrame11p& other);
virtual ~AirFrame11p();
AirFrame11p& operator=(const AirFrame11p& other);
virtual AirFrame11p *dup() const override {return new AirFrame11p(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual bool getUnderMinPowerLevel() const;
virtual void setUnderMinPowerLevel(bool underMinPowerLevel);
virtual bool getWasTransmitting() const;
virtual void setWasTransmitting(bool wasTransmitting);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const AirFrame11p& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, AirFrame11p& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_AIRFRAME11P_M_H
| 2,391 | 26.494253 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/BaseFrame1609_4_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/BaseFrame1609_4.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "BaseFrame1609_4_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(BaseFrame1609_4)
BaseFrame1609_4::BaseFrame1609_4(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->channelNumber = 0;
this->userPriority = 7;
this->psid = 0;
this->recipientAddress = -1;
}
BaseFrame1609_4::BaseFrame1609_4(const BaseFrame1609_4& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
BaseFrame1609_4::~BaseFrame1609_4()
{
}
BaseFrame1609_4& BaseFrame1609_4::operator=(const BaseFrame1609_4& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void BaseFrame1609_4::copy(const BaseFrame1609_4& other)
{
this->channelNumber = other.channelNumber;
this->userPriority = other.userPriority;
this->psid = other.psid;
this->recipientAddress = other.recipientAddress;
}
void BaseFrame1609_4::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->channelNumber);
doParsimPacking(b,this->userPriority);
doParsimPacking(b,this->psid);
doParsimPacking(b,this->recipientAddress);
}
void BaseFrame1609_4::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->channelNumber);
doParsimUnpacking(b,this->userPriority);
doParsimUnpacking(b,this->psid);
doParsimUnpacking(b,this->recipientAddress);
}
int BaseFrame1609_4::getChannelNumber() const
{
return this->channelNumber;
}
void BaseFrame1609_4::setChannelNumber(int channelNumber)
{
this->channelNumber = channelNumber;
}
int BaseFrame1609_4::getUserPriority() const
{
return this->userPriority;
}
void BaseFrame1609_4::setUserPriority(int userPriority)
{
this->userPriority = userPriority;
}
int BaseFrame1609_4::getPsid() const
{
return this->psid;
}
void BaseFrame1609_4::setPsid(int psid)
{
this->psid = psid;
}
LAddress::L2Type& BaseFrame1609_4::getRecipientAddress()
{
return this->recipientAddress;
}
void BaseFrame1609_4::setRecipientAddress(const LAddress::L2Type& recipientAddress)
{
this->recipientAddress = recipientAddress;
}
class BaseFrame1609_4Descriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
BaseFrame1609_4Descriptor();
virtual ~BaseFrame1609_4Descriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(BaseFrame1609_4Descriptor)
BaseFrame1609_4Descriptor::BaseFrame1609_4Descriptor() : omnetpp::cClassDescriptor("veins::BaseFrame1609_4", "omnetpp::cPacket")
{
propertynames = nullptr;
}
BaseFrame1609_4Descriptor::~BaseFrame1609_4Descriptor()
{
delete[] propertynames;
}
bool BaseFrame1609_4Descriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<BaseFrame1609_4 *>(obj)!=nullptr;
}
const char **BaseFrame1609_4Descriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *BaseFrame1609_4Descriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int BaseFrame1609_4Descriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount() : 4;
}
unsigned int BaseFrame1609_4Descriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISCOMPOUND,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *BaseFrame1609_4Descriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"channelNumber",
"userPriority",
"psid",
"recipientAddress",
};
return (field>=0 && field<4) ? fieldNames[field] : nullptr;
}
int BaseFrame1609_4Descriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='c' && strcmp(fieldName, "channelNumber")==0) return base+0;
if (fieldName[0]=='u' && strcmp(fieldName, "userPriority")==0) return base+1;
if (fieldName[0]=='p' && strcmp(fieldName, "psid")==0) return base+2;
if (fieldName[0]=='r' && strcmp(fieldName, "recipientAddress")==0) return base+3;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *BaseFrame1609_4Descriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
"LAddress::L2Type",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr;
}
const char **BaseFrame1609_4Descriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *BaseFrame1609_4Descriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int BaseFrame1609_4Descriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *BaseFrame1609_4Descriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string BaseFrame1609_4Descriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getChannelNumber());
case 1: return long2string(pp->getUserPriority());
case 2: return long2string(pp->getPsid());
case 3: {std::stringstream out; out << pp->getRecipientAddress(); return out.str();}
default: return "";
}
}
bool BaseFrame1609_4Descriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp;
switch (field) {
case 0: pp->setChannelNumber(string2long(value)); return true;
case 1: pp->setUserPriority(string2long(value)); return true;
case 2: pp->setPsid(string2long(value)); return true;
default: return false;
}
}
const char *BaseFrame1609_4Descriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 3: return omnetpp::opp_typename(typeid(LAddress::L2Type));
default: return nullptr;
};
}
void *BaseFrame1609_4Descriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
BaseFrame1609_4 *pp = (BaseFrame1609_4 *)object; (void)pp;
switch (field) {
case 3: return (void *)(&pp->getRecipientAddress()); break;
default: return nullptr;
}
}
} // namespace veins
| 16,613 | 30.706107 | 128 | cc |
null | AICP-main/veins/src/veins/modules/messages/BaseFrame1609_4_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/BaseFrame1609_4.msg.
//
#ifndef __VEINS_BASEFRAME1609_4_M_H
#define __VEINS_BASEFRAME1609_4_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/utils/SimpleAddress.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/BaseFrame1609_4.msg:31</tt> by nedtool.
* <pre>
* packet BaseFrame1609_4
* {
* //Channel Number on which this packet was sent
* int channelNumber;
* //User priority with which this packet was sent (note the AC mapping rules in Mac1609_4::mapUserPriority)
* int userPriority = 7;
* //Unique number to identify the service
* int psid = 0;
* //Recipient of frame (-1 for any)
* LAddress::L2Type recipientAddress = -1;
* }
* </pre>
*/
class VEINS_API BaseFrame1609_4 : public ::omnetpp::cPacket
{
protected:
int channelNumber;
int userPriority;
int psid;
LAddress::L2Type recipientAddress;
private:
void copy(const BaseFrame1609_4& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const BaseFrame1609_4&);
public:
BaseFrame1609_4(const char *name=nullptr, short kind=0);
BaseFrame1609_4(const BaseFrame1609_4& other);
virtual ~BaseFrame1609_4();
BaseFrame1609_4& operator=(const BaseFrame1609_4& other);
virtual BaseFrame1609_4 *dup() const override {return new BaseFrame1609_4(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual int getChannelNumber() const;
virtual void setChannelNumber(int channelNumber);
virtual int getUserPriority() const;
virtual void setUserPriority(int userPriority);
virtual int getPsid() const;
virtual void setPsid(int psid);
virtual LAddress::L2Type& getRecipientAddress();
virtual const LAddress::L2Type& getRecipientAddress() const {return const_cast<BaseFrame1609_4*>(this)->getRecipientAddress();}
virtual void setRecipientAddress(const LAddress::L2Type& recipientAddress);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const BaseFrame1609_4& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, BaseFrame1609_4& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_BASEFRAME1609_4_M_H
| 2,987 | 30.125 | 131 | h |
null | AICP-main/veins/src/veins/modules/messages/DemoSafetyMessage_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoSafetyMessage.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "DemoSafetyMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(DemoSafetyMessage)
DemoSafetyMessage::DemoSafetyMessage(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind)
{
this->serial = 0;
this->angle = 0;
}
DemoSafetyMessage::DemoSafetyMessage(const DemoSafetyMessage& other) : ::veins::BaseFrame1609_4(other)
{
copy(other);
}
DemoSafetyMessage::~DemoSafetyMessage()
{
}
DemoSafetyMessage& DemoSafetyMessage::operator=(const DemoSafetyMessage& other)
{
if (this==&other) return *this;
::veins::BaseFrame1609_4::operator=(other);
copy(other);
return *this;
}
void DemoSafetyMessage::copy(const DemoSafetyMessage& other)
{
this->senderPos = other.senderPos;
this->senderSpeed = other.senderSpeed;
this->serial = other.serial;
this->angle = other.angle;
}
void DemoSafetyMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::BaseFrame1609_4::parsimPack(b);
doParsimPacking(b,this->senderPos);
doParsimPacking(b,this->senderSpeed);
doParsimPacking(b,this->serial);
doParsimPacking(b,this->angle);
}
void DemoSafetyMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::BaseFrame1609_4::parsimUnpack(b);
doParsimUnpacking(b,this->senderPos);
doParsimUnpacking(b,this->senderSpeed);
doParsimUnpacking(b,this->serial);
doParsimUnpacking(b,this->angle);
}
Coord& DemoSafetyMessage::getSenderPos()
{
return this->senderPos;
}
void DemoSafetyMessage::setSenderPos(const Coord& senderPos)
{
this->senderPos = senderPos;
}
Coord& DemoSafetyMessage::getSenderSpeed()
{
return this->senderSpeed;
}
void DemoSafetyMessage::setSenderSpeed(const Coord& senderSpeed)
{
this->senderSpeed = senderSpeed;
}
int DemoSafetyMessage::getSerial() const
{
return this->serial;
}
void DemoSafetyMessage::setSerial(int serial)
{
this->serial = serial;
}
double DemoSafetyMessage::getAngle() const
{
return this->angle;
}
void DemoSafetyMessage::setAngle(double angle)
{
this->angle = angle;
}
class DemoSafetyMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
DemoSafetyMessageDescriptor();
virtual ~DemoSafetyMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(DemoSafetyMessageDescriptor)
DemoSafetyMessageDescriptor::DemoSafetyMessageDescriptor() : omnetpp::cClassDescriptor("veins::DemoSafetyMessage", "veins::BaseFrame1609_4")
{
propertynames = nullptr;
}
DemoSafetyMessageDescriptor::~DemoSafetyMessageDescriptor()
{
delete[] propertynames;
}
bool DemoSafetyMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<DemoSafetyMessage *>(obj)!=nullptr;
}
const char **DemoSafetyMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *DemoSafetyMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int DemoSafetyMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount() : 4;
}
unsigned int DemoSafetyMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISCOMPOUND,
FD_ISCOMPOUND,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *DemoSafetyMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"senderPos",
"senderSpeed",
"serial",
"angle",
};
return (field>=0 && field<4) ? fieldNames[field] : nullptr;
}
int DemoSafetyMessageDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "senderPos")==0) return base+0;
if (fieldName[0]=='s' && strcmp(fieldName, "senderSpeed")==0) return base+1;
if (fieldName[0]=='s' && strcmp(fieldName, "serial")==0) return base+2;
if (fieldName[0]=='a' && strcmp(fieldName, "angle")==0) return base+3;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *DemoSafetyMessageDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"Coord",
"Coord",
"int",
"float",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr;
}
const char **DemoSafetyMessageDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *DemoSafetyMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int DemoSafetyMessageDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *DemoSafetyMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string DemoSafetyMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp;
switch (field) {
case 0: {std::stringstream out; out << pp->getSenderPos(); return out.str();}
case 1: {std::stringstream out; out << pp->getSenderSpeed(); return out.str();}
case 2: return long2string(pp->getSerial());
case 3: return double2string(pp->getAngle());
default: return "";
}
}
bool DemoSafetyMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp;
switch (field) {
case 2: pp->setSerial(string2long(value)); return true;
case 3: pp->setAngle(string2double(value)); return true;
default: return false;
}
}
const char *DemoSafetyMessageDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 0: return omnetpp::opp_typename(typeid(Coord));
case 1: return omnetpp::opp_typename(typeid(Coord));
default: return nullptr;
};
}
void *DemoSafetyMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
DemoSafetyMessage *pp = (DemoSafetyMessage *)object; (void)pp;
switch (field) {
case 0: return (void *)(&pp->getSenderPos()); break;
case 1: return (void *)(&pp->getSenderSpeed()); break;
default: return nullptr;
}
}
} // namespace veins
| 16,569 | 30.6826 | 140 | cc |
null | AICP-main/veins/src/veins/modules/messages/DemoSafetyMessage_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoSafetyMessage.msg.
//
#ifndef __VEINS_DEMOSAFETYMESSAGE_M_H
#define __VEINS_DEMOSAFETYMESSAGE_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/utils/Coord.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
#include "veins/base/utils/SimpleAddress.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/DemoSafetyMessage.msg:35</tt> by nedtool.
* <pre>
* packet DemoSafetyMessage extends BaseFrame1609_4
* {
* Coord senderPos;
* Coord senderSpeed;
* int serial = 0;
* double angle = 0;
* }
* </pre>
*/
class VEINS_API DemoSafetyMessage : public ::veins::BaseFrame1609_4
{
protected:
Coord senderPos;
Coord senderSpeed;
int serial;
double angle;
private:
void copy(const DemoSafetyMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const DemoSafetyMessage&);
public:
DemoSafetyMessage(const char *name=nullptr, short kind=0);
DemoSafetyMessage(const DemoSafetyMessage& other);
virtual ~DemoSafetyMessage();
DemoSafetyMessage& operator=(const DemoSafetyMessage& other);
virtual DemoSafetyMessage *dup() const override {return new DemoSafetyMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual Coord& getSenderPos();
virtual const Coord& getSenderPos() const {return const_cast<DemoSafetyMessage*>(this)->getSenderPos();}
virtual void setSenderPos(const Coord& senderPos);
virtual Coord& getSenderSpeed();
virtual const Coord& getSenderSpeed() const {return const_cast<DemoSafetyMessage*>(this)->getSenderSpeed();}
virtual void setSenderSpeed(const Coord& senderSpeed);
virtual int getSerial() const;
virtual void setSerial(int serial);
virtual double getAngle() const;
virtual void setAngle(double angle);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const DemoSafetyMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, DemoSafetyMessage& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_DEMOSAFETYMESSAGE_M_H
| 2,883 | 29.357895 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/DemoServiceAdvertisement_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoServiceAdvertisement.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "DemoServiceAdvertisement_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(DemoServiceAdvertisment)
DemoServiceAdvertisment::DemoServiceAdvertisment(const char *name, short kind) : ::veins::BaseFrame1609_4(name,kind)
{
this->targetChannel = 0;
}
DemoServiceAdvertisment::DemoServiceAdvertisment(const DemoServiceAdvertisment& other) : ::veins::BaseFrame1609_4(other)
{
copy(other);
}
DemoServiceAdvertisment::~DemoServiceAdvertisment()
{
}
DemoServiceAdvertisment& DemoServiceAdvertisment::operator=(const DemoServiceAdvertisment& other)
{
if (this==&other) return *this;
::veins::BaseFrame1609_4::operator=(other);
copy(other);
return *this;
}
void DemoServiceAdvertisment::copy(const DemoServiceAdvertisment& other)
{
this->targetChannel = other.targetChannel;
this->serviceDescription = other.serviceDescription;
}
void DemoServiceAdvertisment::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::BaseFrame1609_4::parsimPack(b);
doParsimPacking(b,this->targetChannel);
doParsimPacking(b,this->serviceDescription);
}
void DemoServiceAdvertisment::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::BaseFrame1609_4::parsimUnpack(b);
doParsimUnpacking(b,this->targetChannel);
doParsimUnpacking(b,this->serviceDescription);
}
int DemoServiceAdvertisment::getTargetChannel() const
{
return this->targetChannel;
}
void DemoServiceAdvertisment::setTargetChannel(int targetChannel)
{
this->targetChannel = targetChannel;
}
const char * DemoServiceAdvertisment::getServiceDescription() const
{
return this->serviceDescription.c_str();
}
void DemoServiceAdvertisment::setServiceDescription(const char * serviceDescription)
{
this->serviceDescription = serviceDescription;
}
class DemoServiceAdvertismentDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
DemoServiceAdvertismentDescriptor();
virtual ~DemoServiceAdvertismentDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(DemoServiceAdvertismentDescriptor)
DemoServiceAdvertismentDescriptor::DemoServiceAdvertismentDescriptor() : omnetpp::cClassDescriptor("veins::DemoServiceAdvertisment", "veins::BaseFrame1609_4")
{
propertynames = nullptr;
}
DemoServiceAdvertismentDescriptor::~DemoServiceAdvertismentDescriptor()
{
delete[] propertynames;
}
bool DemoServiceAdvertismentDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<DemoServiceAdvertisment *>(obj)!=nullptr;
}
const char **DemoServiceAdvertismentDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *DemoServiceAdvertismentDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int DemoServiceAdvertismentDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount() : 2;
}
unsigned int DemoServiceAdvertismentDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *DemoServiceAdvertismentDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"targetChannel",
"serviceDescription",
};
return (field>=0 && field<2) ? fieldNames[field] : nullptr;
}
int DemoServiceAdvertismentDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='t' && strcmp(fieldName, "targetChannel")==0) return base+0;
if (fieldName[0]=='s' && strcmp(fieldName, "serviceDescription")==0) return base+1;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *DemoServiceAdvertismentDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"int",
"string",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr;
}
const char **DemoServiceAdvertismentDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *DemoServiceAdvertismentDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int DemoServiceAdvertismentDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *DemoServiceAdvertismentDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string DemoServiceAdvertismentDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getTargetChannel());
case 1: return oppstring2string(pp->getServiceDescription());
default: return "";
}
}
bool DemoServiceAdvertismentDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp;
switch (field) {
case 0: pp->setTargetChannel(string2long(value)); return true;
case 1: pp->setServiceDescription((value)); return true;
default: return false;
}
}
const char *DemoServiceAdvertismentDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *DemoServiceAdvertismentDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
DemoServiceAdvertisment *pp = (DemoServiceAdvertisment *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 15,878 | 31.943983 | 158 | cc |
null | AICP-main/veins/src/veins/modules/messages/DemoServiceAdvertisement_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/DemoServiceAdvertisement.msg.
//
#ifndef __VEINS_DEMOSERVICEADVERTISEMENT_M_H
#define __VEINS_DEMOSERVICEADVERTISEMENT_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/utils/Coord.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/DemoServiceAdvertisement.msg:33</tt> by nedtool.
* <pre>
* packet DemoServiceAdvertisment extends BaseFrame1609_4
* {
* int targetChannel;
* string serviceDescription;
* }
* </pre>
*/
class VEINS_API DemoServiceAdvertisment : public ::veins::BaseFrame1609_4
{
protected:
int targetChannel;
::omnetpp::opp_string serviceDescription;
private:
void copy(const DemoServiceAdvertisment& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const DemoServiceAdvertisment&);
public:
DemoServiceAdvertisment(const char *name=nullptr, short kind=0);
DemoServiceAdvertisment(const DemoServiceAdvertisment& other);
virtual ~DemoServiceAdvertisment();
DemoServiceAdvertisment& operator=(const DemoServiceAdvertisment& other);
virtual DemoServiceAdvertisment *dup() const override {return new DemoServiceAdvertisment(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual int getTargetChannel() const;
virtual void setTargetChannel(int targetChannel);
virtual const char * getServiceDescription() const;
virtual void setServiceDescription(const char * serviceDescription);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const DemoServiceAdvertisment& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, DemoServiceAdvertisment& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_DEMOSERVICEADVERTISEMENT_M_H
| 2,575 | 29.666667 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/Mac80211Ack_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Ack.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "Mac80211Ack_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(Mac80211Ack)
Mac80211Ack::Mac80211Ack(const char *name, short kind) : ::veins::Mac80211Pkt(name,kind)
{
this->messageId = 0;
}
Mac80211Ack::Mac80211Ack(const Mac80211Ack& other) : ::veins::Mac80211Pkt(other)
{
copy(other);
}
Mac80211Ack::~Mac80211Ack()
{
}
Mac80211Ack& Mac80211Ack::operator=(const Mac80211Ack& other)
{
if (this==&other) return *this;
::veins::Mac80211Pkt::operator=(other);
copy(other);
return *this;
}
void Mac80211Ack::copy(const Mac80211Ack& other)
{
this->messageId = other.messageId;
}
void Mac80211Ack::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::Mac80211Pkt::parsimPack(b);
doParsimPacking(b,this->messageId);
}
void Mac80211Ack::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::Mac80211Pkt::parsimUnpack(b);
doParsimUnpacking(b,this->messageId);
}
unsigned long Mac80211Ack::getMessageId() const
{
return this->messageId;
}
void Mac80211Ack::setMessageId(unsigned long messageId)
{
this->messageId = messageId;
}
class Mac80211AckDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
Mac80211AckDescriptor();
virtual ~Mac80211AckDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(Mac80211AckDescriptor)
Mac80211AckDescriptor::Mac80211AckDescriptor() : omnetpp::cClassDescriptor("veins::Mac80211Ack", "veins::Mac80211Pkt")
{
propertynames = nullptr;
}
Mac80211AckDescriptor::~Mac80211AckDescriptor()
{
delete[] propertynames;
}
bool Mac80211AckDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<Mac80211Ack *>(obj)!=nullptr;
}
const char **Mac80211AckDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *Mac80211AckDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int Mac80211AckDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 1+basedesc->getFieldCount() : 1;
}
unsigned int Mac80211AckDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
};
return (field>=0 && field<1) ? fieldTypeFlags[field] : 0;
}
const char *Mac80211AckDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"messageId",
};
return (field>=0 && field<1) ? fieldNames[field] : nullptr;
}
int Mac80211AckDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='m' && strcmp(fieldName, "messageId")==0) return base+0;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *Mac80211AckDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"unsigned long",
};
return (field>=0 && field<1) ? fieldTypeStrings[field] : nullptr;
}
const char **Mac80211AckDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *Mac80211AckDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int Mac80211AckDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *Mac80211AckDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string Mac80211AckDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp;
switch (field) {
case 0: return ulong2string(pp->getMessageId());
default: return "";
}
}
bool Mac80211AckDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp;
switch (field) {
case 0: pp->setMessageId(string2ulong(value)); return true;
default: return false;
}
}
const char *Mac80211AckDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *Mac80211AckDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
Mac80211Ack *pp = (Mac80211Ack *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 14,454 | 30.220302 | 128 | cc |
null | AICP-main/veins/src/veins/modules/messages/Mac80211Ack_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Ack.msg.
//
#ifndef __VEINS_MAC80211ACK_M_H
#define __VEINS_MAC80211ACK_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/modules/messages/Mac80211Pkt_m.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/Mac80211Ack.msg:31</tt> by nedtool.
* <pre>
* packet Mac80211Ack extends Mac80211Pkt
* {
* unsigned long messageId; // The ID of the aknowledged packet
* }
* </pre>
*/
class VEINS_API Mac80211Ack : public ::veins::Mac80211Pkt
{
protected:
unsigned long messageId;
private:
void copy(const Mac80211Ack& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const Mac80211Ack&);
public:
Mac80211Ack(const char *name=nullptr, short kind=0);
Mac80211Ack(const Mac80211Ack& other);
virtual ~Mac80211Ack();
Mac80211Ack& operator=(const Mac80211Ack& other);
virtual Mac80211Ack *dup() const override {return new Mac80211Ack(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual unsigned long getMessageId() const;
virtual void setMessageId(unsigned long messageId);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const Mac80211Ack& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, Mac80211Ack& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_MAC80211ACK_M_H
| 2,145 | 26.164557 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/Mac80211Pkt_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Pkt.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "Mac80211Pkt_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(Mac80211Pkt)
Mac80211Pkt::Mac80211Pkt(const char *name, short kind) : ::veins::MacPkt(name,kind)
{
this->address3 = 0;
this->address4 = 0;
this->fragmentation = 0;
this->informationDS = 0;
this->sequenceControl = 0;
this->retry = false;
this->duration = 0;
}
Mac80211Pkt::Mac80211Pkt(const Mac80211Pkt& other) : ::veins::MacPkt(other)
{
copy(other);
}
Mac80211Pkt::~Mac80211Pkt()
{
}
Mac80211Pkt& Mac80211Pkt::operator=(const Mac80211Pkt& other)
{
if (this==&other) return *this;
::veins::MacPkt::operator=(other);
copy(other);
return *this;
}
void Mac80211Pkt::copy(const Mac80211Pkt& other)
{
this->address3 = other.address3;
this->address4 = other.address4;
this->fragmentation = other.fragmentation;
this->informationDS = other.informationDS;
this->sequenceControl = other.sequenceControl;
this->retry = other.retry;
this->duration = other.duration;
}
void Mac80211Pkt::parsimPack(omnetpp::cCommBuffer *b) const
{
::veins::MacPkt::parsimPack(b);
doParsimPacking(b,this->address3);
doParsimPacking(b,this->address4);
doParsimPacking(b,this->fragmentation);
doParsimPacking(b,this->informationDS);
doParsimPacking(b,this->sequenceControl);
doParsimPacking(b,this->retry);
doParsimPacking(b,this->duration);
}
void Mac80211Pkt::parsimUnpack(omnetpp::cCommBuffer *b)
{
::veins::MacPkt::parsimUnpack(b);
doParsimUnpacking(b,this->address3);
doParsimUnpacking(b,this->address4);
doParsimUnpacking(b,this->fragmentation);
doParsimUnpacking(b,this->informationDS);
doParsimUnpacking(b,this->sequenceControl);
doParsimUnpacking(b,this->retry);
doParsimUnpacking(b,this->duration);
}
int Mac80211Pkt::getAddress3() const
{
return this->address3;
}
void Mac80211Pkt::setAddress3(int address3)
{
this->address3 = address3;
}
int Mac80211Pkt::getAddress4() const
{
return this->address4;
}
void Mac80211Pkt::setAddress4(int address4)
{
this->address4 = address4;
}
int Mac80211Pkt::getFragmentation() const
{
return this->fragmentation;
}
void Mac80211Pkt::setFragmentation(int fragmentation)
{
this->fragmentation = fragmentation;
}
int Mac80211Pkt::getInformationDS() const
{
return this->informationDS;
}
void Mac80211Pkt::setInformationDS(int informationDS)
{
this->informationDS = informationDS;
}
int Mac80211Pkt::getSequenceControl() const
{
return this->sequenceControl;
}
void Mac80211Pkt::setSequenceControl(int sequenceControl)
{
this->sequenceControl = sequenceControl;
}
bool Mac80211Pkt::getRetry() const
{
return this->retry;
}
void Mac80211Pkt::setRetry(bool retry)
{
this->retry = retry;
}
::omnetpp::simtime_t Mac80211Pkt::getDuration() const
{
return this->duration;
}
void Mac80211Pkt::setDuration(::omnetpp::simtime_t duration)
{
this->duration = duration;
}
class Mac80211PktDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
Mac80211PktDescriptor();
virtual ~Mac80211PktDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(Mac80211PktDescriptor)
Mac80211PktDescriptor::Mac80211PktDescriptor() : omnetpp::cClassDescriptor("veins::Mac80211Pkt", "veins::MacPkt")
{
propertynames = nullptr;
}
Mac80211PktDescriptor::~Mac80211PktDescriptor()
{
delete[] propertynames;
}
bool Mac80211PktDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<Mac80211Pkt *>(obj)!=nullptr;
}
const char **Mac80211PktDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *Mac80211PktDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int Mac80211PktDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 7+basedesc->getFieldCount() : 7;
}
unsigned int Mac80211PktDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<7) ? fieldTypeFlags[field] : 0;
}
const char *Mac80211PktDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"address3",
"address4",
"fragmentation",
"informationDS",
"sequenceControl",
"retry",
"duration",
};
return (field>=0 && field<7) ? fieldNames[field] : nullptr;
}
int Mac80211PktDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='a' && strcmp(fieldName, "address3")==0) return base+0;
if (fieldName[0]=='a' && strcmp(fieldName, "address4")==0) return base+1;
if (fieldName[0]=='f' && strcmp(fieldName, "fragmentation")==0) return base+2;
if (fieldName[0]=='i' && strcmp(fieldName, "informationDS")==0) return base+3;
if (fieldName[0]=='s' && strcmp(fieldName, "sequenceControl")==0) return base+4;
if (fieldName[0]=='r' && strcmp(fieldName, "retry")==0) return base+5;
if (fieldName[0]=='d' && strcmp(fieldName, "duration")==0) return base+6;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *Mac80211PktDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
"int",
"int",
"bool",
"simtime_t",
};
return (field>=0 && field<7) ? fieldTypeStrings[field] : nullptr;
}
const char **Mac80211PktDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *Mac80211PktDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int Mac80211PktDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *Mac80211PktDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string Mac80211PktDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getAddress3());
case 1: return long2string(pp->getAddress4());
case 2: return long2string(pp->getFragmentation());
case 3: return long2string(pp->getInformationDS());
case 4: return long2string(pp->getSequenceControl());
case 5: return bool2string(pp->getRetry());
case 6: return simtime2string(pp->getDuration());
default: return "";
}
}
bool Mac80211PktDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp;
switch (field) {
case 0: pp->setAddress3(string2long(value)); return true;
case 1: pp->setAddress4(string2long(value)); return true;
case 2: pp->setFragmentation(string2long(value)); return true;
case 3: pp->setInformationDS(string2long(value)); return true;
case 4: pp->setSequenceControl(string2long(value)); return true;
case 5: pp->setRetry(string2bool(value)); return true;
case 6: pp->setDuration(string2simtime(value)); return true;
default: return false;
}
}
const char *Mac80211PktDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *Mac80211PktDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
Mac80211Pkt *pp = (Mac80211Pkt *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 17,922 | 29.74271 | 128 | cc |
null | AICP-main/veins/src/veins/modules/messages/Mac80211Pkt_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/Mac80211Pkt.msg.
//
#ifndef __VEINS_MAC80211PKT_M_H
#define __VEINS_MAC80211PKT_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
// cplusplus {{
#include "veins/base/messages/MacPkt_m.h"
// }}
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/Mac80211Pkt.msg:39</tt> by nedtool.
* <pre>
* //
* // Defines all fields of an 802.11 MAC frame
* //
* packet Mac80211Pkt extends MacPkt
* {
* int address3;
* int address4;
* int fragmentation; //part of the Frame Control field
* int informationDS; //part of the Frame Control field
* int sequenceControl;
* bool retry;
* simtime_t duration; //the expected remaining duration the current transaction
* }
* </pre>
*/
class VEINS_API Mac80211Pkt : public ::veins::MacPkt
{
protected:
int address3;
int address4;
int fragmentation;
int informationDS;
int sequenceControl;
bool retry;
::omnetpp::simtime_t duration;
private:
void copy(const Mac80211Pkt& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const Mac80211Pkt&);
public:
Mac80211Pkt(const char *name=nullptr, short kind=0);
Mac80211Pkt(const Mac80211Pkt& other);
virtual ~Mac80211Pkt();
Mac80211Pkt& operator=(const Mac80211Pkt& other);
virtual Mac80211Pkt *dup() const override {return new Mac80211Pkt(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual int getAddress3() const;
virtual void setAddress3(int address3);
virtual int getAddress4() const;
virtual void setAddress4(int address4);
virtual int getFragmentation() const;
virtual void setFragmentation(int fragmentation);
virtual int getInformationDS() const;
virtual void setInformationDS(int informationDS);
virtual int getSequenceControl() const;
virtual void setSequenceControl(int sequenceControl);
virtual bool getRetry() const;
virtual void setRetry(bool retry);
virtual ::omnetpp::simtime_t getDuration() const;
virtual void setDuration(::omnetpp::simtime_t duration);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const Mac80211Pkt& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, Mac80211Pkt& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_MAC80211PKT_M_H
| 3,084 | 28.103774 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/PhyControlMessage_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/PhyControlMessage.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "PhyControlMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(PhyControlMessage)
PhyControlMessage::PhyControlMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind)
{
this->mcs = -1;
this->txPower_mW = -1;
}
PhyControlMessage::PhyControlMessage(const PhyControlMessage& other) : ::omnetpp::cMessage(other)
{
copy(other);
}
PhyControlMessage::~PhyControlMessage()
{
}
PhyControlMessage& PhyControlMessage::operator=(const PhyControlMessage& other)
{
if (this==&other) return *this;
::omnetpp::cMessage::operator=(other);
copy(other);
return *this;
}
void PhyControlMessage::copy(const PhyControlMessage& other)
{
this->mcs = other.mcs;
this->txPower_mW = other.txPower_mW;
}
void PhyControlMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cMessage::parsimPack(b);
doParsimPacking(b,this->mcs);
doParsimPacking(b,this->txPower_mW);
}
void PhyControlMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cMessage::parsimUnpack(b);
doParsimUnpacking(b,this->mcs);
doParsimUnpacking(b,this->txPower_mW);
}
int PhyControlMessage::getMcs() const
{
return this->mcs;
}
void PhyControlMessage::setMcs(int mcs)
{
this->mcs = mcs;
}
double PhyControlMessage::getTxPower_mW() const
{
return this->txPower_mW;
}
void PhyControlMessage::setTxPower_mW(double txPower_mW)
{
this->txPower_mW = txPower_mW;
}
class PhyControlMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
PhyControlMessageDescriptor();
virtual ~PhyControlMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(PhyControlMessageDescriptor)
PhyControlMessageDescriptor::PhyControlMessageDescriptor() : omnetpp::cClassDescriptor("veins::PhyControlMessage", "omnetpp::cMessage")
{
propertynames = nullptr;
}
PhyControlMessageDescriptor::~PhyControlMessageDescriptor()
{
delete[] propertynames;
}
bool PhyControlMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<PhyControlMessage *>(obj)!=nullptr;
}
const char **PhyControlMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *PhyControlMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int PhyControlMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount() : 2;
}
unsigned int PhyControlMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *PhyControlMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"mcs",
"txPower_mW",
};
return (field>=0 && field<2) ? fieldNames[field] : nullptr;
}
int PhyControlMessageDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='m' && strcmp(fieldName, "mcs")==0) return base+0;
if (fieldName[0]=='t' && strcmp(fieldName, "txPower_mW")==0) return base+1;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *PhyControlMessageDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"int",
"double",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr;
}
const char **PhyControlMessageDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *PhyControlMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int PhyControlMessageDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *PhyControlMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string PhyControlMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getMcs());
case 1: return double2string(pp->getTxPower_mW());
default: return "";
}
}
bool PhyControlMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp;
switch (field) {
case 0: pp->setMcs(string2long(value)); return true;
case 1: pp->setTxPower_mW(string2double(value)); return true;
default: return false;
}
}
const char *PhyControlMessageDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *PhyControlMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
PhyControlMessage *pp = (PhyControlMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 15,260 | 30.596273 | 135 | cc |
null | AICP-main/veins/src/veins/modules/messages/PhyControlMessage_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/PhyControlMessage.msg.
//
#ifndef __VEINS_PHYCONTROLMESSAGE_M_H
#define __VEINS_PHYCONTROLMESSAGE_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
namespace veins {
/**
* Class generated from <tt>veins/modules/messages/PhyControlMessage.msg:29</tt> by nedtool.
* <pre>
* //
* // Defines a control message that can be associated with a MAC frame to set
* // transmission power and datarate on a per packet basis
* //
* message PhyControlMessage
* {
* //modulation and coding scheme to be used (see enum TxMCS in ConstsPhy.h)
* int mcs = -1;
* //transmission power to be used in mW
* double txPower_mW = -1;
* }
* </pre>
*/
class VEINS_API PhyControlMessage : public ::omnetpp::cMessage
{
protected:
int mcs;
double txPower_mW;
private:
void copy(const PhyControlMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const PhyControlMessage&);
public:
PhyControlMessage(const char *name=nullptr, short kind=0);
PhyControlMessage(const PhyControlMessage& other);
virtual ~PhyControlMessage();
PhyControlMessage& operator=(const PhyControlMessage& other);
virtual PhyControlMessage *dup() const override {return new PhyControlMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual int getMcs() const;
virtual void setMcs(int mcs);
virtual double getTxPower_mW() const;
virtual void setTxPower_mW(double txPower_mW);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const PhyControlMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, PhyControlMessage& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_PHYCONTROLMESSAGE_M_H
| 2,485 | 28.247059 | 121 | h |
null | AICP-main/veins/src/veins/modules/messages/TraCITrafficLightMessage_m.cc | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/TraCITrafficLightMessage.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "TraCITrafficLightMessage_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace veins {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
EXECUTE_ON_STARTUP(
omnetpp::cEnum *e = omnetpp::cEnum::find("veins::TrafficLightAtrributeType");
if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("veins::TrafficLightAtrributeType"));
e->insert(NONE, "NONE");
e->insert(LOGICID, "LOGICID");
e->insert(PHASEID, "PHASEID");
e->insert(SWITCHTIME, "SWITCHTIME");
e->insert(STATE, "STATE");
)
EXECUTE_ON_STARTUP(
omnetpp::cEnum *e = omnetpp::cEnum::find("veins::TrafficLightChangeSource");
if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("veins::TrafficLightChangeSource"));
e->insert(UNKNOWN, "UNKNOWN");
e->insert(SUMO, "SUMO");
e->insert(LOGIC, "LOGIC");
e->insert(RSU, "RSU");
)
Register_Class(TraCITrafficLightMessage)
TraCITrafficLightMessage::TraCITrafficLightMessage(const char *name, short kind) : ::omnetpp::cMessage(name,kind)
{
this->changedAttribute = 0;
this->changeSource = 0;
}
TraCITrafficLightMessage::TraCITrafficLightMessage(const TraCITrafficLightMessage& other) : ::omnetpp::cMessage(other)
{
copy(other);
}
TraCITrafficLightMessage::~TraCITrafficLightMessage()
{
}
TraCITrafficLightMessage& TraCITrafficLightMessage::operator=(const TraCITrafficLightMessage& other)
{
if (this==&other) return *this;
::omnetpp::cMessage::operator=(other);
copy(other);
return *this;
}
void TraCITrafficLightMessage::copy(const TraCITrafficLightMessage& other)
{
this->tlId = other.tlId;
this->changedAttribute = other.changedAttribute;
this->oldValue = other.oldValue;
this->newValue = other.newValue;
this->changeSource = other.changeSource;
}
void TraCITrafficLightMessage::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cMessage::parsimPack(b);
doParsimPacking(b,this->tlId);
doParsimPacking(b,this->changedAttribute);
doParsimPacking(b,this->oldValue);
doParsimPacking(b,this->newValue);
doParsimPacking(b,this->changeSource);
}
void TraCITrafficLightMessage::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cMessage::parsimUnpack(b);
doParsimUnpacking(b,this->tlId);
doParsimUnpacking(b,this->changedAttribute);
doParsimUnpacking(b,this->oldValue);
doParsimUnpacking(b,this->newValue);
doParsimUnpacking(b,this->changeSource);
}
const char * TraCITrafficLightMessage::getTlId() const
{
return this->tlId.c_str();
}
void TraCITrafficLightMessage::setTlId(const char * tlId)
{
this->tlId = tlId;
}
int TraCITrafficLightMessage::getChangedAttribute() const
{
return this->changedAttribute;
}
void TraCITrafficLightMessage::setChangedAttribute(int changedAttribute)
{
this->changedAttribute = changedAttribute;
}
const char * TraCITrafficLightMessage::getOldValue() const
{
return this->oldValue.c_str();
}
void TraCITrafficLightMessage::setOldValue(const char * oldValue)
{
this->oldValue = oldValue;
}
const char * TraCITrafficLightMessage::getNewValue() const
{
return this->newValue.c_str();
}
void TraCITrafficLightMessage::setNewValue(const char * newValue)
{
this->newValue = newValue;
}
int TraCITrafficLightMessage::getChangeSource() const
{
return this->changeSource;
}
void TraCITrafficLightMessage::setChangeSource(int changeSource)
{
this->changeSource = changeSource;
}
class TraCITrafficLightMessageDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
TraCITrafficLightMessageDescriptor();
virtual ~TraCITrafficLightMessageDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(TraCITrafficLightMessageDescriptor)
TraCITrafficLightMessageDescriptor::TraCITrafficLightMessageDescriptor() : omnetpp::cClassDescriptor("veins::TraCITrafficLightMessage", "omnetpp::cMessage")
{
propertynames = nullptr;
}
TraCITrafficLightMessageDescriptor::~TraCITrafficLightMessageDescriptor()
{
delete[] propertynames;
}
bool TraCITrafficLightMessageDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<TraCITrafficLightMessage *>(obj)!=nullptr;
}
const char **TraCITrafficLightMessageDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *TraCITrafficLightMessageDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int TraCITrafficLightMessageDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 5+basedesc->getFieldCount() : 5;
}
unsigned int TraCITrafficLightMessageDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<5) ? fieldTypeFlags[field] : 0;
}
const char *TraCITrafficLightMessageDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"tlId",
"changedAttribute",
"oldValue",
"newValue",
"changeSource",
};
return (field>=0 && field<5) ? fieldNames[field] : nullptr;
}
int TraCITrafficLightMessageDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='t' && strcmp(fieldName, "tlId")==0) return base+0;
if (fieldName[0]=='c' && strcmp(fieldName, "changedAttribute")==0) return base+1;
if (fieldName[0]=='o' && strcmp(fieldName, "oldValue")==0) return base+2;
if (fieldName[0]=='n' && strcmp(fieldName, "newValue")==0) return base+3;
if (fieldName[0]=='c' && strcmp(fieldName, "changeSource")==0) return base+4;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *TraCITrafficLightMessageDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"int",
"string",
"string",
"int",
};
return (field>=0 && field<5) ? fieldTypeStrings[field] : nullptr;
}
const char **TraCITrafficLightMessageDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 1: {
static const char *names[] = { "enum", nullptr };
return names;
}
case 4: {
static const char *names[] = { "enum", nullptr };
return names;
}
default: return nullptr;
}
}
const char *TraCITrafficLightMessageDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
case 1:
if (!strcmp(propertyname,"enum")) return "veins::TrafficLightAtrributeType";
return nullptr;
case 4:
if (!strcmp(propertyname,"enum")) return "veins::TrafficLightChangeSource";
return nullptr;
default: return nullptr;
}
}
int TraCITrafficLightMessageDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *TraCITrafficLightMessageDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string TraCITrafficLightMessageDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getTlId());
case 1: return enum2string(pp->getChangedAttribute(), "veins::TrafficLightAtrributeType");
case 2: return oppstring2string(pp->getOldValue());
case 3: return oppstring2string(pp->getNewValue());
case 4: return enum2string(pp->getChangeSource(), "veins::TrafficLightChangeSource");
default: return "";
}
}
bool TraCITrafficLightMessageDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp;
switch (field) {
case 0: pp->setTlId((value)); return true;
case 1: pp->setChangedAttribute((veins::TrafficLightAtrributeType)string2enum(value, "veins::TrafficLightAtrributeType")); return true;
case 2: pp->setOldValue((value)); return true;
case 3: pp->setNewValue((value)); return true;
case 4: pp->setChangeSource((veins::TrafficLightChangeSource)string2enum(value, "veins::TrafficLightChangeSource")); return true;
default: return false;
}
}
const char *TraCITrafficLightMessageDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *TraCITrafficLightMessageDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
TraCITrafficLightMessage *pp = (TraCITrafficLightMessage *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace veins
| 18,952 | 32.076789 | 156 | cc |
null | AICP-main/veins/src/veins/modules/messages/TraCITrafficLightMessage_m.h | //
// Generated file, do not edit! Created by nedtool 5.5 from veins/modules/messages/TraCITrafficLightMessage.msg.
//
#ifndef __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H
#define __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0505
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
// dll export symbol
#ifndef VEINS_API
# if defined(VEINS_EXPORT)
# define VEINS_API OPP_DLLEXPORT
# elif defined(VEINS_IMPORT)
# define VEINS_API OPP_DLLIMPORT
# else
# define VEINS_API
# endif
#endif
namespace veins {
/**
* Enum generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:26</tt> by nedtool.
* <pre>
* enum TrafficLightAtrributeType
* {
* NONE = 0;
* LOGICID = 1;
* PHASEID = 2;
* SWITCHTIME = 3;
* STATE = 4;
* }
* </pre>
*/
enum TrafficLightAtrributeType {
NONE = 0,
LOGICID = 1,
PHASEID = 2,
SWITCHTIME = 3,
STATE = 4
};
/**
* Enum generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:34</tt> by nedtool.
* <pre>
* enum TrafficLightChangeSource
* {
* UNKNOWN = 0;
* SUMO = 1;
* LOGIC = 2;
* RSU = 3;//If an RSU tries to change the values
* }
* </pre>
*/
enum TrafficLightChangeSource {
UNKNOWN = 0,
SUMO = 1,
LOGIC = 2,
RSU = 3
};
/**
* Class generated from <tt>veins/modules/messages/TraCITrafficLightMessage.msg:42</tt> by nedtool.
* <pre>
* // NOTE: Currently only supports changes of the IDs (due to variation in field types)
* message TraCITrafficLightMessage
* {
* // traffic light id
* string tlId;
* // what field/attrbute of the traffic light changed?
* int changedAttribute \@enum(TrafficLightAtrributeType);
* // value before the change
* string oldValue;
* // value that is to be set / was newly set
* string newValue;
* // where did the change originate
* int changeSource \@enum(TrafficLightChangeSource);
* }
* </pre>
*/
class VEINS_API TraCITrafficLightMessage : public ::omnetpp::cMessage
{
protected:
::omnetpp::opp_string tlId;
int changedAttribute;
::omnetpp::opp_string oldValue;
::omnetpp::opp_string newValue;
int changeSource;
private:
void copy(const TraCITrafficLightMessage& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TraCITrafficLightMessage&);
public:
TraCITrafficLightMessage(const char *name=nullptr, short kind=0);
TraCITrafficLightMessage(const TraCITrafficLightMessage& other);
virtual ~TraCITrafficLightMessage();
TraCITrafficLightMessage& operator=(const TraCITrafficLightMessage& other);
virtual TraCITrafficLightMessage *dup() const override {return new TraCITrafficLightMessage(*this);}
virtual void parsimPack(omnetpp::cCommBuffer *b) const override;
virtual void parsimUnpack(omnetpp::cCommBuffer *b) override;
// field getter/setter methods
virtual const char * getTlId() const;
virtual void setTlId(const char * tlId);
virtual int getChangedAttribute() const;
virtual void setChangedAttribute(int changedAttribute);
virtual const char * getOldValue() const;
virtual void setOldValue(const char * oldValue);
virtual const char * getNewValue() const;
virtual void setNewValue(const char * newValue);
virtual int getChangeSource() const;
virtual void setChangeSource(int changeSource);
};
inline void doParsimPacking(omnetpp::cCommBuffer *b, const TraCITrafficLightMessage& obj) {obj.parsimPack(b);}
inline void doParsimUnpacking(omnetpp::cCommBuffer *b, TraCITrafficLightMessage& obj) {obj.parsimUnpack(b);}
} // namespace veins
#endif // ifndef __VEINS_TRACITRAFFICLIGHTMESSAGE_M_H
| 3,978 | 28.043796 | 121 | h |
null | AICP-main/veins/src/veins/modules/mobility/LinearMobility.cc | //
// Copyright (C) 2005 Emin Ilker Cetinbas
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com)
#include "veins/modules/mobility/LinearMobility.h"
#include "veins/veins.h"
using namespace veins;
Define_Module(veins::LinearMobility);
void LinearMobility::initialize(int stage)
{
BaseMobility::initialize(stage);
EV_TRACE << "initializing LinearMobility stage " << stage << endl;
if (stage == 0) {
move.setSpeed(par("speed").doubleValue());
acceleration = par("acceleration");
angle = par("angle");
angle = fmod(angle, 360);
}
else if (stage == 1) {
stepTarget = move.getStartPos();
}
}
void LinearMobility::fixIfHostGetsOutside()
{
Coord dummy = Coord::ZERO;
handleIfOutside(WRAP, stepTarget, dummy, dummy, angle);
}
/**
* Move the host if the destination is not reached yet. Otherwise
* calculate a new random position
*/
void LinearMobility::makeMove()
{
EV_TRACE << "start makeMove " << move.info() << endl;
move.setStart(stepTarget, simTime());
stepTarget.x = (move.getStartPos().x + move.getSpeed() * cos(M_PI * angle / 180) * SIMTIME_DBL(updateInterval));
stepTarget.y = (move.getStartPos().y + move.getSpeed() * sin(M_PI * angle / 180) * SIMTIME_DBL(updateInterval));
move.setDirectionByTarget(stepTarget);
EV_TRACE << "new stepTarget: " << stepTarget.info() << endl;
// accelerate
move.setSpeed(move.getSpeed() + acceleration * SIMTIME_DBL(updateInterval));
fixIfHostGetsOutside();
}
| 2,357 | 29.230769 | 116 | cc |
null | AICP-main/veins/src/veins/modules/mobility/LinearMobility.h | //
// Copyright (C) 2005 Emin Ilker Cetinbas
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// author: Emin Ilker Cetinbas (niw3_at_yahoo_d0t_com)
// part of: framework implementation developed by tkn
#pragma once
#include "veins/base/modules/BaseMobility.h"
namespace veins {
/**
* @brief Linear movement model. See NED file for more info.
*
* This mobility module expects a torus as playground ("useTorus"
* Parameter of BaseWorldUtility module).
*
* NOTE: Does not yet support 3-dimensional movement.
* @ingroup mobility
* @author Emin Ilker Cetinbas
*/
class VEINS_API LinearMobility : public BaseMobility {
protected:
double angle; ///< angle of linear motion
double acceleration; ///< acceleration of linear motion
/** @brief always stores the last step for position display update */
Coord stepTarget;
public:
/** @brief Initializes mobility model parameters.*/
void initialize(int) override;
protected:
/** @brief Move the host*/
void makeMove() override;
void fixIfHostGetsOutside() override;
};
} // namespace veins
| 1,878 | 29.306452 | 76 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/ParBuffer.h | //
// Copyright (C) 2019 Michele Segata <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <cstddef>
#include <string>
#include <sstream>
namespace veins {
class VEINS_API ParBuffer {
public:
ParBuffer()
: SEP(':')
{
}
ParBuffer(std::string buf)
: SEP(':')
{
inBuffer = buf;
}
template <typename T>
ParBuffer& operator<<(const T& v)
{
if (outBuffer.str().length() == 0)
outBuffer << v;
else
outBuffer << SEP << v;
return *this;
}
std::string next()
{
std::string value;
size_t sep;
if (inBuffer.size() == 0) return "";
sep = inBuffer.find(SEP);
if (sep == std::string::npos) {
value = inBuffer;
inBuffer = "";
}
else {
value = inBuffer.substr(0, sep);
inBuffer = inBuffer.substr(sep + 1);
}
return value;
}
ParBuffer& operator>>(double& v)
{
std::string value = next();
sscanf(value.c_str(), "%lf", &v);
return *this;
}
ParBuffer& operator>>(int& v)
{
std::string value = next();
sscanf(value.c_str(), "%d", &v);
return *this;
}
ParBuffer& operator>>(std::string& v)
{
v = next();
return *this;
}
void set(std::string buf)
{
inBuffer = buf;
}
void clear()
{
outBuffer.clear();
}
std::string str() const
{
return outBuffer.str();
}
private:
const char SEP;
std::stringstream outBuffer;
std::string inBuffer;
};
} // namespace veins
| 2,488 | 21.423423 | 76 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIBuffer.cc | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/TraCICoord.h"
#include <iomanip>
#include <sstream>
using namespace veins::TraCIConstants;
namespace veins {
bool TraCIBuffer::timeAsDouble = true;
TraCIBuffer::TraCIBuffer()
: buf()
{
buf_index = 0;
}
TraCIBuffer::TraCIBuffer(std::string buf)
: buf(buf)
{
buf_index = 0;
}
bool TraCIBuffer::eof() const
{
return buf_index == buf.length();
}
void TraCIBuffer::set(std::string buf)
{
this->buf = buf;
buf_index = 0;
}
void TraCIBuffer::clear()
{
set("");
}
std::string TraCIBuffer::str() const
{
return buf;
}
template <>
std::vector<std::string> TraCIBuffer::readTypeChecked(int expectedTraCIType)
{
ASSERT(read<uint8_t>() == static_cast<uint8_t>(expectedTraCIType));
int32_t nrOfElements = read<uint8_t>();
std::vector<std::string> result;
result.reserve(nrOfElements);
for (int32_t i = 0; i < nrOfElements; ++i) {
result.emplace_back(read<std::string>());
}
return result;
}
std::string TraCIBuffer::hexStr() const
{
std::stringstream ss;
for (std::string::const_iterator i = buf.begin() + buf_index; i != buf.end(); ++i) {
if (i != buf.begin()) ss << " ";
ss << std::hex << std::setw(2) << std::setfill('0') << (int) (uint8_t) *i;
}
return ss.str();
}
template <>
void TraCIBuffer::write(std::string inv)
{
uint32_t length = inv.length();
write<uint32_t>(length);
for (size_t i = 0; i < length; ++i) write<char>(inv[i]);
}
template <>
std::string TraCIBuffer::read()
{
uint32_t length = read<uint32_t>();
if (length == 0) return std::string();
char obuf[length + 1];
for (size_t i = 0; i < length; ++i) read<char>(obuf[i]);
obuf[length] = 0;
return std::string(obuf, length);
}
template <>
void TraCIBuffer::write(TraCICoord inv)
{
write<uint8_t>(POSITION_2D);
write<double>(inv.x);
write<double>(inv.y);
}
template <>
TraCICoord TraCIBuffer::read()
{
uint8_t posType = read<uint8_t>();
ASSERT(posType == POSITION_2D);
TraCICoord p;
p.x = read<double>();
p.y = read<double>();
return p;
}
template <>
void TraCIBuffer::write(simtime_t o)
{
if (timeAsDouble) {
double d = o.dbl();
write<double>(d);
}
else {
uint32_t i = o.inUnit(SIMTIME_MS);
write<uint32_t>(i);
}
}
template <>
simtime_t TraCIBuffer::read()
{
if (timeAsDouble) {
double d = read<double>();
simtime_t o = d;
return o;
}
else {
uint32_t i = read<uint32_t>();
simtime_t o = SimTime(i, SIMTIME_MS);
return o;
}
}
bool VEINS_API isBigEndian()
{
short a = 0x0102;
unsigned char* p_a = reinterpret_cast<unsigned char*>(&a);
return (p_a[0] == 0x01);
}
} // namespace veins
| 3,810 | 21.28655 | 88 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIBuffer.h | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <cstddef>
#include <string>
#include "veins/veins.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
namespace veins {
struct TraCICoord;
bool VEINS_API isBigEndian();
/**
* Byte-buffer that stores values in TraCI byte-order
*/
class VEINS_API TraCIBuffer {
public:
TraCIBuffer();
TraCIBuffer(std::string buf);
template <typename T>
T read()
{
T buf_to_return;
unsigned char* p_buf_to_return = reinterpret_cast<unsigned char*>(&buf_to_return);
if (isBigEndian()) {
for (size_t i = 0; i < sizeof(buf_to_return); ++i) {
if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
p_buf_to_return[i] = buf[buf_index++];
}
}
else {
for (size_t i = 0; i < sizeof(buf_to_return); ++i) {
if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
p_buf_to_return[sizeof(buf_to_return) - 1 - i] = buf[buf_index++];
}
}
return buf_to_return;
}
template <typename T>
void write(T inv)
{
unsigned char* p_buf_to_send = reinterpret_cast<unsigned char*>(&inv);
if (isBigEndian()) {
for (size_t i = 0; i < sizeof(inv); ++i) {
buf += p_buf_to_send[i];
}
}
else {
for (size_t i = 0; i < sizeof(inv); ++i) {
buf += p_buf_to_send[sizeof(inv) - 1 - i];
}
}
}
void readBuffer(unsigned char* buffer, size_t size)
{
if (isBigEndian()) {
for (size_t i = 0; i < size; ++i) {
if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
buffer[i] = buf[buf_index++];
}
}
else {
for (size_t i = 0; i < size; ++i) {
if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
buffer[size - 1 - i] = buf[buf_index++];
}
}
}
template <typename T>
T read(T& out)
{
out = read<T>();
return out;
}
template <typename T>
TraCIBuffer& operator>>(T& out)
{
out = read<T>();
return *this;
}
template <typename T>
TraCIBuffer& operator<<(const T& inv)
{
write(inv);
return *this;
}
/**
* @brief
* read and check type, then read and return an item from the buffer
*/
template <typename T>
T readTypeChecked(int expectedTraCIType)
{
uint8_t read_type(read<uint8_t>());
ASSERT(read_type == static_cast<uint8_t>(expectedTraCIType));
return read<T>();
}
bool eof() const;
void set(std::string buf);
void clear();
std::string str() const;
std::string hexStr() const;
static void setTimeType(uint8_t val)
{
if (val != TraCIConstants::TYPE_INTEGER && val != TraCIConstants::TYPE_DOUBLE) {
throw cRuntimeError("Invalid time data type");
}
timeAsDouble = val == TraCIConstants::TYPE_DOUBLE;
}
private:
std::string buf;
size_t buf_index;
static bool timeAsDouble;
};
template <>
std::vector<std::string> TraCIBuffer::readTypeChecked(int expectedTraCIType);
template <>
void VEINS_API TraCIBuffer::write(std::string inv);
template <>
void TraCIBuffer::write(TraCICoord inv);
template <>
std::string VEINS_API TraCIBuffer::read();
template <>
TraCICoord TraCIBuffer::read();
template <>
void TraCIBuffer::write(simtime_t o);
template <>
simtime_t TraCIBuffer::read();
} // namespace veins
| 4,581 | 25.952941 | 92 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIColor.cc | //
// Copyright (C) 2006-2011 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCIColor.h"
using veins::TraCIColor;
TraCIColor::TraCIColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)
: red(red)
, green(green)
, blue(blue)
, alpha(alpha)
{
}
TraCIColor TraCIColor::fromTkColor(std::string tkColorName)
{
if (tkColorName == "alice blue") return TraCIColor(240, 248, 255, 255);
if (tkColorName == "AliceBlue") return TraCIColor(240, 248, 255, 255);
if (tkColorName == "antique white") return TraCIColor(250, 235, 215, 255);
if (tkColorName == "AntiqueWhite") return TraCIColor(250, 235, 215, 255);
if (tkColorName == "AntiqueWhite1") return TraCIColor(255, 239, 219, 255);
if (tkColorName == "AntiqueWhite2") return TraCIColor(238, 223, 204, 255);
if (tkColorName == "AntiqueWhite3") return TraCIColor(205, 192, 176, 255);
if (tkColorName == "AntiqueWhite4") return TraCIColor(139, 131, 120, 255);
if (tkColorName == "aquamarine") return TraCIColor(127, 255, 212, 255);
if (tkColorName == "aquamarine1") return TraCIColor(127, 255, 212, 255);
if (tkColorName == "aquamarine2") return TraCIColor(118, 238, 198, 255);
if (tkColorName == "aquamarine3") return TraCIColor(102, 205, 170, 255);
if (tkColorName == "aquamarine4") return TraCIColor(69, 139, 116, 255);
if (tkColorName == "azure") return TraCIColor(240, 255, 255, 255);
if (tkColorName == "azure1") return TraCIColor(240, 255, 255, 255);
if (tkColorName == "azure2") return TraCIColor(224, 238, 238, 255);
if (tkColorName == "azure3") return TraCIColor(193, 205, 205, 255);
if (tkColorName == "azure4") return TraCIColor(131, 139, 139, 255);
if (tkColorName == "beige") return TraCIColor(245, 245, 220, 255);
if (tkColorName == "bisque") return TraCIColor(255, 228, 196, 255);
if (tkColorName == "bisque1") return TraCIColor(255, 228, 196, 255);
if (tkColorName == "bisque2") return TraCIColor(238, 213, 183, 255);
if (tkColorName == "bisque3") return TraCIColor(205, 183, 158, 255);
if (tkColorName == "bisque4") return TraCIColor(139, 125, 107, 255);
if (tkColorName == "black") return TraCIColor(0, 0, 0, 255);
if (tkColorName == "blanched almond") return TraCIColor(255, 235, 205, 255);
if (tkColorName == "BlanchedAlmond") return TraCIColor(255, 235, 205, 255);
if (tkColorName == "blue") return TraCIColor(0, 0, 255, 255);
if (tkColorName == "blue violet") return TraCIColor(138, 43, 226, 255);
if (tkColorName == "blue1") return TraCIColor(0, 0, 255, 255);
if (tkColorName == "blue2") return TraCIColor(0, 0, 238, 255);
if (tkColorName == "blue3") return TraCIColor(0, 0, 205, 255);
if (tkColorName == "blue4") return TraCIColor(0, 0, 139, 255);
if (tkColorName == "BlueViolet") return TraCIColor(138, 43, 226, 255);
if (tkColorName == "brown") return TraCIColor(165, 42, 42, 255);
if (tkColorName == "brown1") return TraCIColor(255, 64, 64, 255);
if (tkColorName == "brown2") return TraCIColor(238, 59, 59, 255);
if (tkColorName == "brown3") return TraCIColor(205, 51, 51, 255);
if (tkColorName == "brown4") return TraCIColor(139, 35, 35, 255);
if (tkColorName == "burlywood") return TraCIColor(222, 184, 135, 255);
if (tkColorName == "burlywood1") return TraCIColor(255, 211, 155, 255);
if (tkColorName == "burlywood2") return TraCIColor(238, 197, 145, 255);
if (tkColorName == "burlywood3") return TraCIColor(205, 170, 125, 255);
if (tkColorName == "burlywood4") return TraCIColor(139, 115, 85, 255);
if (tkColorName == "cadet blue") return TraCIColor(95, 158, 160, 255);
if (tkColorName == "CadetBlue") return TraCIColor(95, 158, 160, 255);
if (tkColorName == "CadetBlue1") return TraCIColor(152, 245, 255, 255);
if (tkColorName == "CadetBlue2") return TraCIColor(142, 229, 238, 255);
if (tkColorName == "CadetBlue3") return TraCIColor(122, 197, 205, 255);
if (tkColorName == "CadetBlue4") return TraCIColor(83, 134, 139, 255);
if (tkColorName == "chartreuse") return TraCIColor(127, 255, 0, 255);
if (tkColorName == "chartreuse1") return TraCIColor(127, 255, 0, 255);
if (tkColorName == "chartreuse2") return TraCIColor(118, 238, 0, 255);
if (tkColorName == "chartreuse3") return TraCIColor(102, 205, 0, 255);
if (tkColorName == "chartreuse4") return TraCIColor(69, 139, 0, 255);
if (tkColorName == "chocolate") return TraCIColor(210, 105, 30, 255);
if (tkColorName == "chocolate1") return TraCIColor(255, 127, 36, 255);
if (tkColorName == "chocolate2") return TraCIColor(238, 118, 33, 255);
if (tkColorName == "chocolate3") return TraCIColor(205, 102, 29, 255);
if (tkColorName == "chocolate4") return TraCIColor(139, 69, 19, 255);
if (tkColorName == "coral") return TraCIColor(255, 127, 80, 255);
if (tkColorName == "coral1") return TraCIColor(255, 114, 86, 255);
if (tkColorName == "coral2") return TraCIColor(238, 106, 80, 255);
if (tkColorName == "coral3") return TraCIColor(205, 91, 69, 255);
if (tkColorName == "coral4") return TraCIColor(139, 62, 47, 255);
if (tkColorName == "cornflower blue") return TraCIColor(100, 149, 237, 255);
if (tkColorName == "CornflowerBlue") return TraCIColor(100, 149, 237, 255);
if (tkColorName == "cornsilk") return TraCIColor(255, 248, 220, 255);
if (tkColorName == "cornsilk1") return TraCIColor(255, 248, 220, 255);
if (tkColorName == "cornsilk2") return TraCIColor(238, 232, 205, 255);
if (tkColorName == "cornsilk3") return TraCIColor(205, 200, 177, 255);
if (tkColorName == "cornsilk4") return TraCIColor(139, 136, 120, 255);
if (tkColorName == "cyan") return TraCIColor(0, 255, 255, 255);
if (tkColorName == "cyan1") return TraCIColor(0, 255, 255, 255);
if (tkColorName == "cyan2") return TraCIColor(0, 238, 238, 255);
if (tkColorName == "cyan3") return TraCIColor(0, 205, 205, 255);
if (tkColorName == "cyan4") return TraCIColor(0, 139, 139, 255);
if (tkColorName == "dark blue") return TraCIColor(0, 0, 139, 255);
if (tkColorName == "dark cyan") return TraCIColor(0, 139, 139, 255);
if (tkColorName == "dark goldenrod") return TraCIColor(184, 134, 11, 255);
if (tkColorName == "dark gray") return TraCIColor(169, 169, 169, 255);
if (tkColorName == "dark green") return TraCIColor(0, 100, 0, 255);
if (tkColorName == "dark grey") return TraCIColor(169, 169, 169, 255);
if (tkColorName == "dark khaki") return TraCIColor(189, 183, 107, 255);
if (tkColorName == "dark magenta") return TraCIColor(139, 0, 139, 255);
if (tkColorName == "dark olive green") return TraCIColor(85, 107, 47, 255);
if (tkColorName == "dark orange") return TraCIColor(255, 140, 0, 255);
if (tkColorName == "dark orchid") return TraCIColor(153, 50, 204, 255);
if (tkColorName == "dark red") return TraCIColor(139, 0, 0, 255);
if (tkColorName == "dark salmon") return TraCIColor(233, 150, 122, 255);
if (tkColorName == "dark sea green") return TraCIColor(143, 188, 143, 255);
if (tkColorName == "dark slate blue") return TraCIColor(72, 61, 139, 255);
if (tkColorName == "dark slate gray") return TraCIColor(47, 79, 79, 255);
if (tkColorName == "dark slate grey") return TraCIColor(47, 79, 79, 255);
if (tkColorName == "dark turquoise") return TraCIColor(0, 206, 209, 255);
if (tkColorName == "dark violet") return TraCIColor(148, 0, 211, 255);
if (tkColorName == "DarkBlue") return TraCIColor(0, 0, 139, 255);
if (tkColorName == "DarkCyan") return TraCIColor(0, 139, 139, 255);
if (tkColorName == "DarkGoldenrod") return TraCIColor(184, 134, 11, 255);
if (tkColorName == "DarkGoldenrod1") return TraCIColor(255, 185, 15, 255);
if (tkColorName == "DarkGoldenrod2") return TraCIColor(238, 173, 14, 255);
if (tkColorName == "DarkGoldenrod3") return TraCIColor(205, 149, 12, 255);
if (tkColorName == "DarkGoldenrod4") return TraCIColor(139, 101, 8, 255);
if (tkColorName == "DarkGray") return TraCIColor(169, 169, 169, 255);
if (tkColorName == "DarkGreen") return TraCIColor(0, 100, 0, 255);
if (tkColorName == "DarkGrey") return TraCIColor(169, 169, 169, 255);
if (tkColorName == "DarkKhaki") return TraCIColor(189, 183, 107, 255);
if (tkColorName == "DarkMagenta") return TraCIColor(139, 0, 139, 255);
if (tkColorName == "DarkOliveGreen") return TraCIColor(85, 107, 47, 255);
if (tkColorName == "DarkOliveGreen1") return TraCIColor(202, 255, 112, 255);
if (tkColorName == "DarkOliveGreen2") return TraCIColor(188, 238, 104, 255);
if (tkColorName == "DarkOliveGreen3") return TraCIColor(162, 205, 90, 255);
if (tkColorName == "DarkOliveGreen4") return TraCIColor(110, 139, 61, 255);
if (tkColorName == "DarkOrange") return TraCIColor(255, 140, 0, 255);
if (tkColorName == "DarkOrange1") return TraCIColor(255, 127, 0, 255);
if (tkColorName == "DarkOrange2") return TraCIColor(238, 118, 0, 255);
if (tkColorName == "DarkOrange3") return TraCIColor(205, 102, 0, 255);
if (tkColorName == "DarkOrange4") return TraCIColor(139, 69, 0, 255);
if (tkColorName == "DarkOrchid") return TraCIColor(153, 50, 204, 255);
if (tkColorName == "DarkOrchid1") return TraCIColor(191, 62, 255, 255);
if (tkColorName == "DarkOrchid2") return TraCIColor(178, 58, 238, 255);
if (tkColorName == "DarkOrchid3") return TraCIColor(154, 50, 205, 255);
if (tkColorName == "DarkOrchid4") return TraCIColor(104, 34, 139, 255);
if (tkColorName == "DarkRed") return TraCIColor(139, 0, 0, 255);
if (tkColorName == "DarkSalmon") return TraCIColor(233, 150, 122, 255);
if (tkColorName == "DarkSeaGreen") return TraCIColor(143, 188, 143, 255);
if (tkColorName == "DarkSeaGreen1") return TraCIColor(193, 255, 193, 255);
if (tkColorName == "DarkSeaGreen2") return TraCIColor(180, 238, 180, 255);
if (tkColorName == "DarkSeaGreen3") return TraCIColor(155, 205, 155, 255);
if (tkColorName == "DarkSeaGreen4") return TraCIColor(105, 139, 105, 255);
if (tkColorName == "DarkSlateBlue") return TraCIColor(72, 61, 139, 255);
if (tkColorName == "DarkSlateGray") return TraCIColor(47, 79, 79, 255);
if (tkColorName == "DarkSlateGray1") return TraCIColor(151, 255, 255, 255);
if (tkColorName == "DarkSlateGray2") return TraCIColor(141, 238, 238, 255);
if (tkColorName == "DarkSlateGray3") return TraCIColor(121, 205, 205, 255);
if (tkColorName == "DarkSlateGray4") return TraCIColor(82, 139, 139, 255);
if (tkColorName == "DarkSlateGrey") return TraCIColor(47, 79, 79, 255);
if (tkColorName == "DarkTurquoise") return TraCIColor(0, 206, 209, 255);
if (tkColorName == "DarkViolet") return TraCIColor(148, 0, 211, 255);
if (tkColorName == "deep pink") return TraCIColor(255, 20, 147, 255);
if (tkColorName == "deep sky blue") return TraCIColor(0, 191, 255, 255);
if (tkColorName == "DeepPink") return TraCIColor(255, 20, 147, 255);
if (tkColorName == "DeepPink1") return TraCIColor(255, 20, 147, 255);
if (tkColorName == "DeepPink2") return TraCIColor(238, 18, 137, 255);
if (tkColorName == "DeepPink3") return TraCIColor(205, 16, 118, 255);
if (tkColorName == "DeepPink4") return TraCIColor(139, 10, 80, 255);
if (tkColorName == "DeepSkyBlue") return TraCIColor(0, 191, 255, 255);
if (tkColorName == "DeepSkyBlue1") return TraCIColor(0, 191, 255, 255);
if (tkColorName == "DeepSkyBlue2") return TraCIColor(0, 178, 238, 255);
if (tkColorName == "DeepSkyBlue3") return TraCIColor(0, 154, 205, 255);
if (tkColorName == "DeepSkyBlue4") return TraCIColor(0, 104, 139, 255);
if (tkColorName == "dim gray") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "dim grey") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "DimGray") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "DimGrey") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "dodger blue") return TraCIColor(30, 144, 255, 255);
if (tkColorName == "DodgerBlue") return TraCIColor(30, 144, 255, 255);
if (tkColorName == "DodgerBlue1") return TraCIColor(30, 144, 255, 255);
if (tkColorName == "DodgerBlue2") return TraCIColor(28, 134, 238, 255);
if (tkColorName == "DodgerBlue3") return TraCIColor(24, 116, 205, 255);
if (tkColorName == "DodgerBlue4") return TraCIColor(16, 78, 139, 255);
if (tkColorName == "firebrick") return TraCIColor(178, 34, 34, 255);
if (tkColorName == "firebrick1") return TraCIColor(255, 48, 48, 255);
if (tkColorName == "firebrick2") return TraCIColor(238, 44, 44, 255);
if (tkColorName == "firebrick3") return TraCIColor(205, 38, 38, 255);
if (tkColorName == "firebrick4") return TraCIColor(139, 26, 26, 255);
if (tkColorName == "floral white") return TraCIColor(255, 250, 240, 255);
if (tkColorName == "FloralWhite") return TraCIColor(255, 250, 240, 255);
if (tkColorName == "forest green") return TraCIColor(34, 139, 34, 255);
if (tkColorName == "ForestGreen") return TraCIColor(34, 139, 34, 255);
if (tkColorName == "gainsboro") return TraCIColor(220, 220, 220, 255);
if (tkColorName == "ghost white") return TraCIColor(248, 248, 255, 255);
if (tkColorName == "GhostWhite") return TraCIColor(248, 248, 255, 255);
if (tkColorName == "gold") return TraCIColor(255, 215, 0, 255);
if (tkColorName == "gold1") return TraCIColor(255, 215, 0, 255);
if (tkColorName == "gold2") return TraCIColor(238, 201, 0, 255);
if (tkColorName == "gold3") return TraCIColor(205, 173, 0, 255);
if (tkColorName == "gold4") return TraCIColor(139, 117, 0, 255);
if (tkColorName == "goldenrod") return TraCIColor(218, 165, 32, 255);
if (tkColorName == "goldenrod1") return TraCIColor(255, 193, 37, 255);
if (tkColorName == "goldenrod2") return TraCIColor(238, 180, 34, 255);
if (tkColorName == "goldenrod3") return TraCIColor(205, 155, 29, 255);
if (tkColorName == "goldenrod4") return TraCIColor(139, 105, 20, 255);
if (tkColorName == "gray") return TraCIColor(190, 190, 190, 255);
if (tkColorName == "gray0") return TraCIColor(0, 0, 0, 255);
if (tkColorName == "gray1") return TraCIColor(3, 3, 3, 255);
if (tkColorName == "gray2") return TraCIColor(5, 5, 5, 255);
if (tkColorName == "gray3") return TraCIColor(8, 8, 8, 255);
if (tkColorName == "gray4") return TraCIColor(10, 10, 10, 255);
if (tkColorName == "gray5") return TraCIColor(13, 13, 13, 255);
if (tkColorName == "gray6") return TraCIColor(15, 15, 15, 255);
if (tkColorName == "gray7") return TraCIColor(18, 18, 18, 255);
if (tkColorName == "gray8") return TraCIColor(20, 20, 20, 255);
if (tkColorName == "gray9") return TraCIColor(23, 23, 23, 255);
if (tkColorName == "gray10") return TraCIColor(26, 26, 26, 255);
if (tkColorName == "gray11") return TraCIColor(28, 28, 28, 255);
if (tkColorName == "gray12") return TraCIColor(31, 31, 31, 255);
if (tkColorName == "gray13") return TraCIColor(33, 33, 33, 255);
if (tkColorName == "gray14") return TraCIColor(36, 36, 36, 255);
if (tkColorName == "gray15") return TraCIColor(38, 38, 38, 255);
if (tkColorName == "gray16") return TraCIColor(41, 41, 41, 255);
if (tkColorName == "gray17") return TraCIColor(43, 43, 43, 255);
if (tkColorName == "gray18") return TraCIColor(46, 46, 46, 255);
if (tkColorName == "gray19") return TraCIColor(48, 48, 48, 255);
if (tkColorName == "gray20") return TraCIColor(51, 51, 51, 255);
if (tkColorName == "gray21") return TraCIColor(54, 54, 54, 255);
if (tkColorName == "gray22") return TraCIColor(56, 56, 56, 255);
if (tkColorName == "gray23") return TraCIColor(59, 59, 59, 255);
if (tkColorName == "gray24") return TraCIColor(61, 61, 61, 255);
if (tkColorName == "gray25") return TraCIColor(64, 64, 64, 255);
if (tkColorName == "gray26") return TraCIColor(66, 66, 66, 255);
if (tkColorName == "gray27") return TraCIColor(69, 69, 69, 255);
if (tkColorName == "gray28") return TraCIColor(71, 71, 71, 255);
if (tkColorName == "gray29") return TraCIColor(74, 74, 74, 255);
if (tkColorName == "gray30") return TraCIColor(77, 77, 77, 255);
if (tkColorName == "gray31") return TraCIColor(79, 79, 79, 255);
if (tkColorName == "gray32") return TraCIColor(82, 82, 82, 255);
if (tkColorName == "gray33") return TraCIColor(84, 84, 84, 255);
if (tkColorName == "gray34") return TraCIColor(87, 87, 87, 255);
if (tkColorName == "gray35") return TraCIColor(89, 89, 89, 255);
if (tkColorName == "gray36") return TraCIColor(92, 92, 92, 255);
if (tkColorName == "gray37") return TraCIColor(94, 94, 94, 255);
if (tkColorName == "gray38") return TraCIColor(97, 97, 97, 255);
if (tkColorName == "gray39") return TraCIColor(99, 99, 99, 255);
if (tkColorName == "gray40") return TraCIColor(102, 102, 102, 255);
if (tkColorName == "gray41") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "gray42") return TraCIColor(107, 107, 107, 255);
if (tkColorName == "gray43") return TraCIColor(110, 110, 110, 255);
if (tkColorName == "gray44") return TraCIColor(112, 112, 112, 255);
if (tkColorName == "gray45") return TraCIColor(115, 115, 115, 255);
if (tkColorName == "gray46") return TraCIColor(117, 117, 117, 255);
if (tkColorName == "gray47") return TraCIColor(120, 120, 120, 255);
if (tkColorName == "gray48") return TraCIColor(122, 122, 122, 255);
if (tkColorName == "gray49") return TraCIColor(125, 125, 125, 255);
if (tkColorName == "gray50") return TraCIColor(127, 127, 127, 255);
if (tkColorName == "gray51") return TraCIColor(130, 130, 130, 255);
if (tkColorName == "gray52") return TraCIColor(133, 133, 133, 255);
if (tkColorName == "gray53") return TraCIColor(135, 135, 135, 255);
if (tkColorName == "gray54") return TraCIColor(138, 138, 138, 255);
if (tkColorName == "gray55") return TraCIColor(140, 140, 140, 255);
if (tkColorName == "gray56") return TraCIColor(143, 143, 143, 255);
if (tkColorName == "gray57") return TraCIColor(145, 145, 145, 255);
if (tkColorName == "gray58") return TraCIColor(148, 148, 148, 255);
if (tkColorName == "gray59") return TraCIColor(150, 150, 150, 255);
if (tkColorName == "gray60") return TraCIColor(153, 153, 153, 255);
if (tkColorName == "gray61") return TraCIColor(156, 156, 156, 255);
if (tkColorName == "gray62") return TraCIColor(158, 158, 158, 255);
if (tkColorName == "gray63") return TraCIColor(161, 161, 161, 255);
if (tkColorName == "gray64") return TraCIColor(163, 163, 163, 255);
if (tkColorName == "gray65") return TraCIColor(166, 166, 166, 255);
if (tkColorName == "gray66") return TraCIColor(168, 168, 168, 255);
if (tkColorName == "gray67") return TraCIColor(171, 171, 171, 255);
if (tkColorName == "gray68") return TraCIColor(173, 173, 173, 255);
if (tkColorName == "gray69") return TraCIColor(176, 176, 176, 255);
if (tkColorName == "gray70") return TraCIColor(179, 179, 179, 255);
if (tkColorName == "gray71") return TraCIColor(181, 181, 181, 255);
if (tkColorName == "gray72") return TraCIColor(184, 184, 184, 255);
if (tkColorName == "gray73") return TraCIColor(186, 186, 186, 255);
if (tkColorName == "gray74") return TraCIColor(189, 189, 189, 255);
if (tkColorName == "gray75") return TraCIColor(191, 191, 191, 255);
if (tkColorName == "gray76") return TraCIColor(194, 194, 194, 255);
if (tkColorName == "gray77") return TraCIColor(196, 196, 196, 255);
if (tkColorName == "gray78") return TraCIColor(199, 199, 199, 255);
if (tkColorName == "gray79") return TraCIColor(201, 201, 201, 255);
if (tkColorName == "gray80") return TraCIColor(204, 204, 204, 255);
if (tkColorName == "gray81") return TraCIColor(207, 207, 207, 255);
if (tkColorName == "gray82") return TraCIColor(209, 209, 209, 255);
if (tkColorName == "gray83") return TraCIColor(212, 212, 212, 255);
if (tkColorName == "gray84") return TraCIColor(214, 214, 214, 255);
if (tkColorName == "gray85") return TraCIColor(217, 217, 217, 255);
if (tkColorName == "gray86") return TraCIColor(219, 219, 219, 255);
if (tkColorName == "gray87") return TraCIColor(222, 222, 222, 255);
if (tkColorName == "gray88") return TraCIColor(224, 224, 224, 255);
if (tkColorName == "gray89") return TraCIColor(227, 227, 227, 255);
if (tkColorName == "gray90") return TraCIColor(229, 229, 229, 255);
if (tkColorName == "gray91") return TraCIColor(232, 232, 232, 255);
if (tkColorName == "gray92") return TraCIColor(235, 235, 235, 255);
if (tkColorName == "gray93") return TraCIColor(237, 237, 237, 255);
if (tkColorName == "gray94") return TraCIColor(240, 240, 240, 255);
if (tkColorName == "gray95") return TraCIColor(242, 242, 242, 255);
if (tkColorName == "gray96") return TraCIColor(245, 245, 245, 255);
if (tkColorName == "gray97") return TraCIColor(247, 247, 247, 255);
if (tkColorName == "gray98") return TraCIColor(250, 250, 250, 255);
if (tkColorName == "gray99") return TraCIColor(252, 252, 252, 255);
if (tkColorName == "gray100") return TraCIColor(255, 255, 255, 255);
if (tkColorName == "green") return TraCIColor(0, 255, 0, 255);
if (tkColorName == "green yellow") return TraCIColor(173, 255, 47, 255);
if (tkColorName == "green1") return TraCIColor(0, 255, 0, 255);
if (tkColorName == "green2") return TraCIColor(0, 238, 0, 255);
if (tkColorName == "green3") return TraCIColor(0, 205, 0, 255);
if (tkColorName == "green4") return TraCIColor(0, 139, 0, 255);
if (tkColorName == "GreenYellow") return TraCIColor(173, 255, 47, 255);
if (tkColorName == "grey") return TraCIColor(190, 190, 190, 255);
if (tkColorName == "grey0") return TraCIColor(0, 0, 0, 255);
if (tkColorName == "grey1") return TraCIColor(3, 3, 3, 255);
if (tkColorName == "grey2") return TraCIColor(5, 5, 5, 255);
if (tkColorName == "grey3") return TraCIColor(8, 8, 8, 255);
if (tkColorName == "grey4") return TraCIColor(10, 10, 10, 255);
if (tkColorName == "grey5") return TraCIColor(13, 13, 13, 255);
if (tkColorName == "grey6") return TraCIColor(15, 15, 15, 255);
if (tkColorName == "grey7") return TraCIColor(18, 18, 18, 255);
if (tkColorName == "grey8") return TraCIColor(20, 20, 20, 255);
if (tkColorName == "grey9") return TraCIColor(23, 23, 23, 255);
if (tkColorName == "grey10") return TraCIColor(26, 26, 26, 255);
if (tkColorName == "grey11") return TraCIColor(28, 28, 28, 255);
if (tkColorName == "grey12") return TraCIColor(31, 31, 31, 255);
if (tkColorName == "grey13") return TraCIColor(33, 33, 33, 255);
if (tkColorName == "grey14") return TraCIColor(36, 36, 36, 255);
if (tkColorName == "grey15") return TraCIColor(38, 38, 38, 255);
if (tkColorName == "grey16") return TraCIColor(41, 41, 41, 255);
if (tkColorName == "grey17") return TraCIColor(43, 43, 43, 255);
if (tkColorName == "grey18") return TraCIColor(46, 46, 46, 255);
if (tkColorName == "grey19") return TraCIColor(48, 48, 48, 255);
if (tkColorName == "grey20") return TraCIColor(51, 51, 51, 255);
if (tkColorName == "grey21") return TraCIColor(54, 54, 54, 255);
if (tkColorName == "grey22") return TraCIColor(56, 56, 56, 255);
if (tkColorName == "grey23") return TraCIColor(59, 59, 59, 255);
if (tkColorName == "grey24") return TraCIColor(61, 61, 61, 255);
if (tkColorName == "grey25") return TraCIColor(64, 64, 64, 255);
if (tkColorName == "grey26") return TraCIColor(66, 66, 66, 255);
if (tkColorName == "grey27") return TraCIColor(69, 69, 69, 255);
if (tkColorName == "grey28") return TraCIColor(71, 71, 71, 255);
if (tkColorName == "grey29") return TraCIColor(74, 74, 74, 255);
if (tkColorName == "grey30") return TraCIColor(77, 77, 77, 255);
if (tkColorName == "grey31") return TraCIColor(79, 79, 79, 255);
if (tkColorName == "grey32") return TraCIColor(82, 82, 82, 255);
if (tkColorName == "grey33") return TraCIColor(84, 84, 84, 255);
if (tkColorName == "grey34") return TraCIColor(87, 87, 87, 255);
if (tkColorName == "grey35") return TraCIColor(89, 89, 89, 255);
if (tkColorName == "grey36") return TraCIColor(92, 92, 92, 255);
if (tkColorName == "grey37") return TraCIColor(94, 94, 94, 255);
if (tkColorName == "grey38") return TraCIColor(97, 97, 97, 255);
if (tkColorName == "grey39") return TraCIColor(99, 99, 99, 255);
if (tkColorName == "grey40") return TraCIColor(102, 102, 102, 255);
if (tkColorName == "grey41") return TraCIColor(105, 105, 105, 255);
if (tkColorName == "grey42") return TraCIColor(107, 107, 107, 255);
if (tkColorName == "grey43") return TraCIColor(110, 110, 110, 255);
if (tkColorName == "grey44") return TraCIColor(112, 112, 112, 255);
if (tkColorName == "grey45") return TraCIColor(115, 115, 115, 255);
if (tkColorName == "grey46") return TraCIColor(117, 117, 117, 255);
if (tkColorName == "grey47") return TraCIColor(120, 120, 120, 255);
if (tkColorName == "grey48") return TraCIColor(122, 122, 122, 255);
if (tkColorName == "grey49") return TraCIColor(125, 125, 125, 255);
if (tkColorName == "grey50") return TraCIColor(127, 127, 127, 255);
if (tkColorName == "grey51") return TraCIColor(130, 130, 130, 255);
if (tkColorName == "grey52") return TraCIColor(133, 133, 133, 255);
if (tkColorName == "grey53") return TraCIColor(135, 135, 135, 255);
if (tkColorName == "grey54") return TraCIColor(138, 138, 138, 255);
if (tkColorName == "grey55") return TraCIColor(140, 140, 140, 255);
if (tkColorName == "grey56") return TraCIColor(143, 143, 143, 255);
if (tkColorName == "grey57") return TraCIColor(145, 145, 145, 255);
if (tkColorName == "grey58") return TraCIColor(148, 148, 148, 255);
if (tkColorName == "grey59") return TraCIColor(150, 150, 150, 255);
if (tkColorName == "grey60") return TraCIColor(153, 153, 153, 255);
if (tkColorName == "grey61") return TraCIColor(156, 156, 156, 255);
if (tkColorName == "grey62") return TraCIColor(158, 158, 158, 255);
if (tkColorName == "grey63") return TraCIColor(161, 161, 161, 255);
if (tkColorName == "grey64") return TraCIColor(163, 163, 163, 255);
if (tkColorName == "grey65") return TraCIColor(166, 166, 166, 255);
if (tkColorName == "grey66") return TraCIColor(168, 168, 168, 255);
if (tkColorName == "grey67") return TraCIColor(171, 171, 171, 255);
if (tkColorName == "grey68") return TraCIColor(173, 173, 173, 255);
if (tkColorName == "grey69") return TraCIColor(176, 176, 176, 255);
if (tkColorName == "grey70") return TraCIColor(179, 179, 179, 255);
if (tkColorName == "grey71") return TraCIColor(181, 181, 181, 255);
if (tkColorName == "grey72") return TraCIColor(184, 184, 184, 255);
if (tkColorName == "grey73") return TraCIColor(186, 186, 186, 255);
if (tkColorName == "grey74") return TraCIColor(189, 189, 189, 255);
if (tkColorName == "grey75") return TraCIColor(191, 191, 191, 255);
if (tkColorName == "grey76") return TraCIColor(194, 194, 194, 255);
if (tkColorName == "grey77") return TraCIColor(196, 196, 196, 255);
if (tkColorName == "grey78") return TraCIColor(199, 199, 199, 255);
if (tkColorName == "grey79") return TraCIColor(201, 201, 201, 255);
if (tkColorName == "grey80") return TraCIColor(204, 204, 204, 255);
if (tkColorName == "grey81") return TraCIColor(207, 207, 207, 255);
if (tkColorName == "grey82") return TraCIColor(209, 209, 209, 255);
if (tkColorName == "grey83") return TraCIColor(212, 212, 212, 255);
if (tkColorName == "grey84") return TraCIColor(214, 214, 214, 255);
if (tkColorName == "grey85") return TraCIColor(217, 217, 217, 255);
if (tkColorName == "grey86") return TraCIColor(219, 219, 219, 255);
if (tkColorName == "grey87") return TraCIColor(222, 222, 222, 255);
if (tkColorName == "grey88") return TraCIColor(224, 224, 224, 255);
if (tkColorName == "grey89") return TraCIColor(227, 227, 227, 255);
if (tkColorName == "grey90") return TraCIColor(229, 229, 229, 255);
if (tkColorName == "grey91") return TraCIColor(232, 232, 232, 255);
if (tkColorName == "grey92") return TraCIColor(235, 235, 235, 255);
if (tkColorName == "grey93") return TraCIColor(237, 237, 237, 255);
if (tkColorName == "grey94") return TraCIColor(240, 240, 240, 255);
if (tkColorName == "grey95") return TraCIColor(242, 242, 242, 255);
if (tkColorName == "grey96") return TraCIColor(245, 245, 245, 255);
if (tkColorName == "grey97") return TraCIColor(247, 247, 247, 255);
if (tkColorName == "grey98") return TraCIColor(250, 250, 250, 255);
if (tkColorName == "grey99") return TraCIColor(252, 252, 252, 255);
if (tkColorName == "grey100") return TraCIColor(255, 255, 255, 255);
if (tkColorName == "honeydew") return TraCIColor(240, 255, 240, 255);
if (tkColorName == "honeydew1") return TraCIColor(240, 255, 240, 255);
if (tkColorName == "honeydew2") return TraCIColor(224, 238, 224, 255);
if (tkColorName == "honeydew3") return TraCIColor(193, 205, 193, 255);
if (tkColorName == "honeydew4") return TraCIColor(131, 139, 131, 255);
if (tkColorName == "hot pink") return TraCIColor(255, 105, 180, 255);
if (tkColorName == "HotPink") return TraCIColor(255, 105, 180, 255);
if (tkColorName == "HotPink1") return TraCIColor(255, 110, 180, 255);
if (tkColorName == "HotPink2") return TraCIColor(238, 106, 167, 255);
if (tkColorName == "HotPink3") return TraCIColor(205, 96, 144, 255);
if (tkColorName == "HotPink4") return TraCIColor(139, 58, 98, 255);
if (tkColorName == "indian red") return TraCIColor(205, 92, 92, 255);
if (tkColorName == "IndianRed") return TraCIColor(205, 92, 92, 255);
if (tkColorName == "IndianRed1") return TraCIColor(255, 106, 106, 255);
if (tkColorName == "IndianRed2") return TraCIColor(238, 99, 99, 255);
if (tkColorName == "IndianRed3") return TraCIColor(205, 85, 85, 255);
if (tkColorName == "IndianRed4") return TraCIColor(139, 58, 58, 255);
if (tkColorName == "ivory") return TraCIColor(255, 255, 240, 255);
if (tkColorName == "ivory1") return TraCIColor(255, 255, 240, 255);
if (tkColorName == "ivory2") return TraCIColor(238, 238, 224, 255);
if (tkColorName == "ivory3") return TraCIColor(205, 205, 193, 255);
if (tkColorName == "ivory4") return TraCIColor(139, 139, 131, 255);
if (tkColorName == "khaki") return TraCIColor(240, 230, 140, 255);
if (tkColorName == "khaki1") return TraCIColor(255, 246, 143, 255);
if (tkColorName == "khaki2") return TraCIColor(238, 230, 133, 255);
if (tkColorName == "khaki3") return TraCIColor(205, 198, 115, 255);
if (tkColorName == "khaki4") return TraCIColor(139, 134, 78, 255);
if (tkColorName == "lavender") return TraCIColor(230, 230, 250, 255);
if (tkColorName == "lavender blush") return TraCIColor(255, 240, 245, 255);
if (tkColorName == "LavenderBlush") return TraCIColor(255, 240, 245, 255);
if (tkColorName == "LavenderBlush1") return TraCIColor(255, 240, 245, 255);
if (tkColorName == "LavenderBlush2") return TraCIColor(238, 224, 229, 255);
if (tkColorName == "LavenderBlush3") return TraCIColor(205, 193, 197, 255);
if (tkColorName == "LavenderBlush4") return TraCIColor(139, 131, 134, 255);
if (tkColorName == "lawn green") return TraCIColor(124, 252, 0, 255);
if (tkColorName == "LawnGreen") return TraCIColor(124, 252, 0, 255);
if (tkColorName == "lemon chiffon") return TraCIColor(255, 250, 205, 255);
if (tkColorName == "LemonChiffon") return TraCIColor(255, 250, 205, 255);
if (tkColorName == "LemonChiffon1") return TraCIColor(255, 250, 205, 255);
if (tkColorName == "LemonChiffon2") return TraCIColor(238, 233, 191, 255);
if (tkColorName == "LemonChiffon3") return TraCIColor(205, 201, 165, 255);
if (tkColorName == "LemonChiffon4") return TraCIColor(139, 137, 112, 255);
if (tkColorName == "light blue") return TraCIColor(173, 216, 230, 255);
if (tkColorName == "light coral") return TraCIColor(240, 128, 128, 255);
if (tkColorName == "light cyan") return TraCIColor(224, 255, 255, 255);
if (tkColorName == "light goldenrod") return TraCIColor(238, 221, 130, 255);
if (tkColorName == "light goldenrod yellow") return TraCIColor(250, 250, 210, 255);
if (tkColorName == "light gray") return TraCIColor(211, 211, 211, 255);
if (tkColorName == "light green") return TraCIColor(144, 238, 144, 255);
if (tkColorName == "light grey") return TraCIColor(211, 211, 211, 255);
if (tkColorName == "light pink") return TraCIColor(255, 182, 193, 255);
if (tkColorName == "light salmon") return TraCIColor(255, 160, 122, 255);
if (tkColorName == "light sea green") return TraCIColor(32, 178, 170, 255);
if (tkColorName == "light sky blue") return TraCIColor(135, 206, 250, 255);
if (tkColorName == "light slate blue") return TraCIColor(132, 112, 255, 255);
if (tkColorName == "light slate gray") return TraCIColor(119, 136, 153, 255);
if (tkColorName == "light slate grey") return TraCIColor(119, 136, 153, 255);
if (tkColorName == "light steel blue") return TraCIColor(176, 196, 222, 255);
if (tkColorName == "light yellow") return TraCIColor(255, 255, 224, 255);
if (tkColorName == "LightBlue") return TraCIColor(173, 216, 230, 255);
if (tkColorName == "LightBlue1") return TraCIColor(191, 239, 255, 255);
if (tkColorName == "LightBlue2") return TraCIColor(178, 223, 238, 255);
if (tkColorName == "LightBlue3") return TraCIColor(154, 192, 205, 255);
if (tkColorName == "LightBlue4") return TraCIColor(104, 131, 139, 255);
if (tkColorName == "LightCoral") return TraCIColor(240, 128, 128, 255);
if (tkColorName == "LightCyan") return TraCIColor(224, 255, 255, 255);
if (tkColorName == "LightCyan1") return TraCIColor(224, 255, 255, 255);
if (tkColorName == "LightCyan2") return TraCIColor(209, 238, 238, 255);
if (tkColorName == "LightCyan3") return TraCIColor(180, 205, 205, 255);
if (tkColorName == "LightCyan4") return TraCIColor(122, 139, 139, 255);
if (tkColorName == "LightGoldenrod") return TraCIColor(238, 221, 130, 255);
if (tkColorName == "LightGoldenrod1") return TraCIColor(255, 236, 139, 255);
if (tkColorName == "LightGoldenrod2") return TraCIColor(238, 220, 130, 255);
if (tkColorName == "LightGoldenrod3") return TraCIColor(205, 190, 112, 255);
if (tkColorName == "LightGoldenrod4") return TraCIColor(139, 129, 76, 255);
if (tkColorName == "LightGoldenrodYellow") return TraCIColor(250, 250, 210, 255);
if (tkColorName == "LightGray") return TraCIColor(211, 211, 211, 255);
if (tkColorName == "LightGreen") return TraCIColor(144, 238, 144, 255);
if (tkColorName == "LightGrey") return TraCIColor(211, 211, 211, 255);
if (tkColorName == "LightPink") return TraCIColor(255, 182, 193, 255);
if (tkColorName == "LightPink1") return TraCIColor(255, 174, 185, 255);
if (tkColorName == "LightPink2") return TraCIColor(238, 162, 173, 255);
if (tkColorName == "LightPink3") return TraCIColor(205, 140, 149, 255);
if (tkColorName == "LightPink4") return TraCIColor(139, 95, 101, 255);
if (tkColorName == "LightSalmon") return TraCIColor(255, 160, 122, 255);
if (tkColorName == "LightSalmon1") return TraCIColor(255, 160, 122, 255);
if (tkColorName == "LightSalmon2") return TraCIColor(238, 149, 114, 255);
if (tkColorName == "LightSalmon3") return TraCIColor(205, 129, 98, 255);
if (tkColorName == "LightSalmon4") return TraCIColor(139, 87, 66, 255);
if (tkColorName == "LightSeaGreen") return TraCIColor(32, 178, 170, 255);
if (tkColorName == "LightSkyBlue") return TraCIColor(135, 206, 250, 255);
if (tkColorName == "LightSkyBlue1") return TraCIColor(176, 226, 255, 255);
if (tkColorName == "LightSkyBlue2") return TraCIColor(164, 211, 238, 255);
if (tkColorName == "LightSkyBlue3") return TraCIColor(141, 182, 205, 255);
if (tkColorName == "LightSkyBlue4") return TraCIColor(96, 123, 139, 255);
if (tkColorName == "LightSlateBlue") return TraCIColor(132, 112, 255, 255);
if (tkColorName == "LightSlateGray") return TraCIColor(119, 136, 153, 255);
if (tkColorName == "LightSlateGrey") return TraCIColor(119, 136, 153, 255);
if (tkColorName == "LightSteelBlue") return TraCIColor(176, 196, 222, 255);
if (tkColorName == "LightSteelBlue1") return TraCIColor(202, 225, 255, 255);
if (tkColorName == "LightSteelBlue2") return TraCIColor(188, 210, 238, 255);
if (tkColorName == "LightSteelBlue3") return TraCIColor(162, 181, 205, 255);
if (tkColorName == "LightSteelBlue4") return TraCIColor(110, 123, 139, 255);
if (tkColorName == "LightYellow") return TraCIColor(255, 255, 224, 255);
if (tkColorName == "LightYellow1") return TraCIColor(255, 255, 224, 255);
if (tkColorName == "LightYellow2") return TraCIColor(238, 238, 209, 255);
if (tkColorName == "LightYellow3") return TraCIColor(205, 205, 180, 255);
if (tkColorName == "LightYellow4") return TraCIColor(139, 139, 122, 255);
if (tkColorName == "lime green") return TraCIColor(50, 205, 50, 255);
if (tkColorName == "LimeGreen") return TraCIColor(50, 205, 50, 255);
if (tkColorName == "linen") return TraCIColor(250, 240, 230, 255);
if (tkColorName == "magenta") return TraCIColor(255, 0, 255, 255);
if (tkColorName == "magenta1") return TraCIColor(255, 0, 255, 255);
if (tkColorName == "magenta2") return TraCIColor(238, 0, 238, 255);
if (tkColorName == "magenta3") return TraCIColor(205, 0, 205, 255);
if (tkColorName == "magenta4") return TraCIColor(139, 0, 139, 255);
if (tkColorName == "maroon") return TraCIColor(176, 48, 96, 255);
if (tkColorName == "maroon1") return TraCIColor(255, 52, 179, 255);
if (tkColorName == "maroon2") return TraCIColor(238, 48, 167, 255);
if (tkColorName == "maroon3") return TraCIColor(205, 41, 144, 255);
if (tkColorName == "maroon4") return TraCIColor(139, 28, 98, 255);
if (tkColorName == "medium aquamarine") return TraCIColor(102, 205, 170, 255);
if (tkColorName == "medium blue") return TraCIColor(0, 0, 205, 255);
if (tkColorName == "medium orchid") return TraCIColor(186, 85, 211, 255);
if (tkColorName == "medium purple") return TraCIColor(147, 112, 219, 255);
if (tkColorName == "medium sea green") return TraCIColor(60, 179, 113, 255);
if (tkColorName == "medium slate blue") return TraCIColor(123, 104, 238, 255);
if (tkColorName == "medium spring green") return TraCIColor(0, 250, 154, 255);
if (tkColorName == "medium turquoise") return TraCIColor(72, 209, 204, 255);
if (tkColorName == "medium violet red") return TraCIColor(199, 21, 133, 255);
if (tkColorName == "MediumAquamarine") return TraCIColor(102, 205, 170, 255);
if (tkColorName == "MediumBlue") return TraCIColor(0, 0, 205, 255);
if (tkColorName == "MediumOrchid") return TraCIColor(186, 85, 211, 255);
if (tkColorName == "MediumOrchid1") return TraCIColor(224, 102, 255, 255);
if (tkColorName == "MediumOrchid2") return TraCIColor(209, 95, 238, 255);
if (tkColorName == "MediumOrchid3") return TraCIColor(180, 82, 205, 255);
if (tkColorName == "MediumOrchid4") return TraCIColor(122, 55, 139, 255);
if (tkColorName == "MediumPurple") return TraCIColor(147, 112, 219, 255);
if (tkColorName == "MediumPurple1") return TraCIColor(171, 130, 255, 255);
if (tkColorName == "MediumPurple2") return TraCIColor(159, 121, 238, 255);
if (tkColorName == "MediumPurple3") return TraCIColor(137, 104, 205, 255);
if (tkColorName == "MediumPurple4") return TraCIColor(93, 71, 139, 255);
if (tkColorName == "MediumSeaGreen") return TraCIColor(60, 179, 113, 255);
if (tkColorName == "MediumSlateBlue") return TraCIColor(123, 104, 238, 255);
if (tkColorName == "MediumSpringGreen") return TraCIColor(0, 250, 154, 255);
if (tkColorName == "MediumTurquoise") return TraCIColor(72, 209, 204, 255);
if (tkColorName == "MediumVioletRed") return TraCIColor(199, 21, 133, 255);
if (tkColorName == "midnight blue") return TraCIColor(25, 25, 112, 255);
if (tkColorName == "MidnightBlue") return TraCIColor(25, 25, 112, 255);
if (tkColorName == "mint cream") return TraCIColor(245, 255, 250, 255);
if (tkColorName == "MintCream") return TraCIColor(245, 255, 250, 255);
if (tkColorName == "misty rose") return TraCIColor(255, 228, 225, 255);
if (tkColorName == "MistyRose") return TraCIColor(255, 228, 225, 255);
if (tkColorName == "MistyRose1") return TraCIColor(255, 228, 225, 255);
if (tkColorName == "MistyRose2") return TraCIColor(238, 213, 210, 255);
if (tkColorName == "MistyRose3") return TraCIColor(205, 183, 181, 255);
if (tkColorName == "MistyRose4") return TraCIColor(139, 125, 123, 255);
if (tkColorName == "moccasin") return TraCIColor(255, 228, 181, 255);
if (tkColorName == "navajo white") return TraCIColor(255, 222, 173, 255);
if (tkColorName == "NavajoWhite") return TraCIColor(255, 222, 173, 255);
if (tkColorName == "NavajoWhite1") return TraCIColor(255, 222, 173, 255);
if (tkColorName == "NavajoWhite2") return TraCIColor(238, 207, 161, 255);
if (tkColorName == "NavajoWhite3") return TraCIColor(205, 179, 139, 255);
if (tkColorName == "NavajoWhite4") return TraCIColor(139, 121, 94, 255);
if (tkColorName == "navy") return TraCIColor(0, 0, 128, 255);
if (tkColorName == "navy blue") return TraCIColor(0, 0, 128, 255);
if (tkColorName == "NavyBlue") return TraCIColor(0, 0, 128, 255);
if (tkColorName == "old lace") return TraCIColor(253, 245, 230, 255);
if (tkColorName == "OldLace") return TraCIColor(253, 245, 230, 255);
if (tkColorName == "olive drab") return TraCIColor(107, 142, 35, 255);
if (tkColorName == "OliveDrab") return TraCIColor(107, 142, 35, 255);
if (tkColorName == "OliveDrab1") return TraCIColor(192, 255, 62, 255);
if (tkColorName == "OliveDrab2") return TraCIColor(179, 238, 58, 255);
if (tkColorName == "OliveDrab3") return TraCIColor(154, 205, 50, 255);
if (tkColorName == "OliveDrab4") return TraCIColor(105, 139, 34, 255);
if (tkColorName == "orange") return TraCIColor(255, 165, 0, 255);
if (tkColorName == "orange red") return TraCIColor(255, 69, 0, 255);
if (tkColorName == "orange1") return TraCIColor(255, 165, 0, 255);
if (tkColorName == "orange2") return TraCIColor(238, 154, 0, 255);
if (tkColorName == "orange3") return TraCIColor(205, 133, 0, 255);
if (tkColorName == "orange4") return TraCIColor(139, 90, 0, 255);
if (tkColorName == "OrangeRed") return TraCIColor(255, 69, 0, 255);
if (tkColorName == "OrangeRed1") return TraCIColor(255, 69, 0, 255);
if (tkColorName == "OrangeRed2") return TraCIColor(238, 64, 0, 255);
if (tkColorName == "OrangeRed3") return TraCIColor(205, 55, 0, 255);
if (tkColorName == "OrangeRed4") return TraCIColor(139, 37, 0, 255);
if (tkColorName == "orchid") return TraCIColor(218, 112, 214, 255);
if (tkColorName == "orchid1") return TraCIColor(255, 131, 250, 255);
if (tkColorName == "orchid2") return TraCIColor(238, 122, 233, 255);
if (tkColorName == "orchid3") return TraCIColor(205, 105, 201, 255);
if (tkColorName == "orchid4") return TraCIColor(139, 71, 137, 255);
if (tkColorName == "pale goldenrod") return TraCIColor(238, 232, 170, 255);
if (tkColorName == "pale green") return TraCIColor(152, 251, 152, 255);
if (tkColorName == "pale turquoise") return TraCIColor(175, 238, 238, 255);
if (tkColorName == "pale violet red") return TraCIColor(219, 112, 147, 255);
if (tkColorName == "PaleGoldenrod") return TraCIColor(238, 232, 170, 255);
if (tkColorName == "PaleGreen") return TraCIColor(152, 251, 152, 255);
if (tkColorName == "PaleGreen1") return TraCIColor(154, 255, 154, 255);
if (tkColorName == "PaleGreen2") return TraCIColor(144, 238, 144, 255);
if (tkColorName == "PaleGreen3") return TraCIColor(124, 205, 124, 255);
if (tkColorName == "PaleGreen4") return TraCIColor(84, 139, 84, 255);
if (tkColorName == "PaleTurquoise") return TraCIColor(175, 238, 238, 255);
if (tkColorName == "PaleTurquoise1") return TraCIColor(187, 255, 255, 255);
if (tkColorName == "PaleTurquoise2") return TraCIColor(174, 238, 238, 255);
if (tkColorName == "PaleTurquoise3") return TraCIColor(150, 205, 205, 255);
if (tkColorName == "PaleTurquoise4") return TraCIColor(102, 139, 139, 255);
if (tkColorName == "PaleVioletRed") return TraCIColor(219, 112, 147, 255);
if (tkColorName == "PaleVioletRed1") return TraCIColor(255, 130, 171, 255);
if (tkColorName == "PaleVioletRed2") return TraCIColor(238, 121, 159, 255);
if (tkColorName == "PaleVioletRed3") return TraCIColor(205, 104, 127, 255);
if (tkColorName == "PaleVioletRed4") return TraCIColor(139, 71, 93, 255);
if (tkColorName == "papaya whip") return TraCIColor(255, 239, 213, 255);
if (tkColorName == "PapayaWhip") return TraCIColor(255, 239, 213, 255);
if (tkColorName == "peach puff") return TraCIColor(255, 218, 185, 255);
if (tkColorName == "PeachPuff") return TraCIColor(255, 218, 185, 255);
if (tkColorName == "PeachPuff1") return TraCIColor(255, 218, 185, 255);
if (tkColorName == "PeachPuff2") return TraCIColor(238, 203, 173, 255);
if (tkColorName == "PeachPuff3") return TraCIColor(205, 175, 149, 255);
if (tkColorName == "PeachPuff4") return TraCIColor(139, 119, 101, 255);
if (tkColorName == "peru") return TraCIColor(205, 133, 63, 255);
if (tkColorName == "pink") return TraCIColor(255, 192, 203, 255);
if (tkColorName == "pink1") return TraCIColor(255, 181, 197, 255);
if (tkColorName == "pink2") return TraCIColor(238, 169, 184, 255);
if (tkColorName == "pink3") return TraCIColor(205, 145, 158, 255);
if (tkColorName == "pink4") return TraCIColor(139, 99, 108, 255);
if (tkColorName == "plum") return TraCIColor(221, 160, 221, 255);
if (tkColorName == "plum1") return TraCIColor(255, 187, 255, 255);
if (tkColorName == "plum2") return TraCIColor(238, 174, 238, 255);
if (tkColorName == "plum3") return TraCIColor(205, 150, 205, 255);
if (tkColorName == "plum4") return TraCIColor(139, 102, 139, 255);
if (tkColorName == "powder blue") return TraCIColor(176, 224, 230, 255);
if (tkColorName == "PowderBlue") return TraCIColor(176, 224, 230, 255);
if (tkColorName == "purple") return TraCIColor(160, 32, 240, 255);
if (tkColorName == "purple1") return TraCIColor(155, 48, 255, 255);
if (tkColorName == "purple2") return TraCIColor(145, 44, 238, 255);
if (tkColorName == "purple3") return TraCIColor(125, 38, 205, 255);
if (tkColorName == "purple4") return TraCIColor(85, 26, 139, 255);
if (tkColorName == "red") return TraCIColor(255, 0, 0, 255);
if (tkColorName == "red1") return TraCIColor(255, 0, 0, 255);
if (tkColorName == "red2") return TraCIColor(238, 0, 0, 255);
if (tkColorName == "red3") return TraCIColor(205, 0, 0, 255);
if (tkColorName == "red4") return TraCIColor(139, 0, 0, 255);
if (tkColorName == "rosy brown") return TraCIColor(188, 143, 143, 255);
if (tkColorName == "RosyBrown") return TraCIColor(188, 143, 143, 255);
if (tkColorName == "RosyBrown1") return TraCIColor(255, 193, 193, 255);
if (tkColorName == "RosyBrown2") return TraCIColor(238, 180, 180, 255);
if (tkColorName == "RosyBrown3") return TraCIColor(205, 155, 155, 255);
if (tkColorName == "RosyBrown4") return TraCIColor(139, 105, 105, 255);
if (tkColorName == "royal blue") return TraCIColor(65, 105, 225, 255);
if (tkColorName == "RoyalBlue") return TraCIColor(65, 105, 225, 255);
if (tkColorName == "RoyalBlue1") return TraCIColor(72, 118, 255, 255);
if (tkColorName == "RoyalBlue2") return TraCIColor(67, 110, 238, 255);
if (tkColorName == "RoyalBlue3") return TraCIColor(58, 95, 205, 255);
if (tkColorName == "RoyalBlue4") return TraCIColor(39, 64, 139, 255);
if (tkColorName == "saddle brown") return TraCIColor(139, 69, 19, 255);
if (tkColorName == "SaddleBrown") return TraCIColor(139, 69, 19, 255);
if (tkColorName == "salmon") return TraCIColor(250, 128, 114, 255);
if (tkColorName == "salmon1") return TraCIColor(255, 140, 105, 255);
if (tkColorName == "salmon2") return TraCIColor(238, 130, 98, 255);
if (tkColorName == "salmon3") return TraCIColor(205, 112, 84, 255);
if (tkColorName == "salmon4") return TraCIColor(139, 76, 57, 255);
if (tkColorName == "sandy brown") return TraCIColor(244, 164, 96, 255);
if (tkColorName == "SandyBrown") return TraCIColor(244, 164, 96, 255);
if (tkColorName == "sea green") return TraCIColor(46, 139, 87, 255);
if (tkColorName == "SeaGreen") return TraCIColor(46, 139, 87, 255);
if (tkColorName == "SeaGreen1") return TraCIColor(84, 255, 159, 255);
if (tkColorName == "SeaGreen2") return TraCIColor(78, 238, 148, 255);
if (tkColorName == "SeaGreen3") return TraCIColor(67, 205, 128, 255);
if (tkColorName == "SeaGreen4") return TraCIColor(46, 139, 87, 255);
if (tkColorName == "seashell") return TraCIColor(255, 245, 238, 255);
if (tkColorName == "seashell1") return TraCIColor(255, 245, 238, 255);
if (tkColorName == "seashell2") return TraCIColor(238, 229, 222, 255);
if (tkColorName == "seashell3") return TraCIColor(205, 197, 191, 255);
if (tkColorName == "seashell4") return TraCIColor(139, 134, 130, 255);
if (tkColorName == "sienna") return TraCIColor(160, 82, 45, 255);
if (tkColorName == "sienna1") return TraCIColor(255, 130, 71, 255);
if (tkColorName == "sienna2") return TraCIColor(238, 121, 66, 255);
if (tkColorName == "sienna3") return TraCIColor(205, 104, 57, 255);
if (tkColorName == "sienna4") return TraCIColor(139, 71, 38, 255);
if (tkColorName == "sky blue") return TraCIColor(135, 206, 235, 255);
if (tkColorName == "SkyBlue") return TraCIColor(135, 206, 235, 255);
if (tkColorName == "SkyBlue1") return TraCIColor(135, 206, 255, 255);
if (tkColorName == "SkyBlue2") return TraCIColor(126, 192, 238, 255);
if (tkColorName == "SkyBlue3") return TraCIColor(108, 166, 205, 255);
if (tkColorName == "SkyBlue4") return TraCIColor(74, 112, 139, 255);
if (tkColorName == "slate blue") return TraCIColor(106, 90, 205, 255);
if (tkColorName == "slate gray") return TraCIColor(112, 128, 144, 255);
if (tkColorName == "slate grey") return TraCIColor(112, 128, 144, 255);
if (tkColorName == "SlateBlue") return TraCIColor(106, 90, 205, 255);
if (tkColorName == "SlateBlue1") return TraCIColor(131, 111, 255, 255);
if (tkColorName == "SlateBlue2") return TraCIColor(122, 103, 238, 255);
if (tkColorName == "SlateBlue3") return TraCIColor(105, 89, 205, 255);
if (tkColorName == "SlateBlue4") return TraCIColor(71, 60, 139, 255);
if (tkColorName == "SlateGray") return TraCIColor(112, 128, 144, 255);
if (tkColorName == "SlateGray1") return TraCIColor(198, 226, 255, 255);
if (tkColorName == "SlateGray2") return TraCIColor(185, 211, 238, 255);
if (tkColorName == "SlateGray3") return TraCIColor(159, 182, 205, 255);
if (tkColorName == "SlateGray4") return TraCIColor(108, 123, 139, 255);
if (tkColorName == "SlateGrey") return TraCIColor(112, 128, 144, 255);
if (tkColorName == "snow") return TraCIColor(255, 250, 250, 255);
if (tkColorName == "snow1") return TraCIColor(255, 250, 250, 255);
if (tkColorName == "snow2") return TraCIColor(238, 233, 233, 255);
if (tkColorName == "snow3") return TraCIColor(205, 201, 201, 255);
if (tkColorName == "snow4") return TraCIColor(139, 137, 137, 255);
if (tkColorName == "spring green") return TraCIColor(0, 255, 127, 255);
if (tkColorName == "SpringGreen") return TraCIColor(0, 255, 127, 255);
if (tkColorName == "SpringGreen1") return TraCIColor(0, 255, 127, 255);
if (tkColorName == "SpringGreen2") return TraCIColor(0, 238, 118, 255);
if (tkColorName == "SpringGreen3") return TraCIColor(0, 205, 102, 255);
if (tkColorName == "SpringGreen4") return TraCIColor(0, 139, 69, 255);
if (tkColorName == "steel blue") return TraCIColor(70, 130, 180, 255);
if (tkColorName == "SteelBlue") return TraCIColor(70, 130, 180, 255);
if (tkColorName == "SteelBlue1") return TraCIColor(99, 184, 255, 255);
if (tkColorName == "SteelBlue2") return TraCIColor(92, 172, 238, 255);
if (tkColorName == "SteelBlue3") return TraCIColor(79, 148, 205, 255);
if (tkColorName == "SteelBlue4") return TraCIColor(54, 100, 139, 255);
if (tkColorName == "tan") return TraCIColor(210, 180, 140, 255);
if (tkColorName == "tan1") return TraCIColor(255, 165, 79, 255);
if (tkColorName == "tan2") return TraCIColor(238, 154, 73, 255);
if (tkColorName == "tan3") return TraCIColor(205, 133, 63, 255);
if (tkColorName == "tan4") return TraCIColor(139, 90, 43, 255);
if (tkColorName == "thistle") return TraCIColor(216, 191, 216, 255);
if (tkColorName == "thistle1") return TraCIColor(255, 225, 255, 255);
if (tkColorName == "thistle2") return TraCIColor(238, 210, 238, 255);
if (tkColorName == "thistle3") return TraCIColor(205, 181, 205, 255);
if (tkColorName == "thistle4") return TraCIColor(139, 123, 139, 255);
if (tkColorName == "tomato") return TraCIColor(255, 99, 71, 255);
if (tkColorName == "tomato1") return TraCIColor(255, 99, 71, 255);
if (tkColorName == "tomato2") return TraCIColor(238, 92, 66, 255);
if (tkColorName == "tomato3") return TraCIColor(205, 79, 57, 255);
if (tkColorName == "tomato4") return TraCIColor(139, 54, 38, 255);
if (tkColorName == "turquoise") return TraCIColor(64, 224, 208, 255);
if (tkColorName == "turquoise1") return TraCIColor(0, 245, 255, 255);
if (tkColorName == "turquoise2") return TraCIColor(0, 229, 238, 255);
if (tkColorName == "turquoise3") return TraCIColor(0, 197, 205, 255);
if (tkColorName == "turquoise4") return TraCIColor(0, 134, 139, 255);
if (tkColorName == "violet") return TraCIColor(238, 130, 238, 255);
if (tkColorName == "violet red") return TraCIColor(208, 32, 144, 255);
if (tkColorName == "VioletRed") return TraCIColor(208, 32, 144, 255);
if (tkColorName == "VioletRed1") return TraCIColor(255, 62, 150, 255);
if (tkColorName == "VioletRed2") return TraCIColor(238, 58, 140, 255);
if (tkColorName == "VioletRed3") return TraCIColor(205, 50, 120, 255);
if (tkColorName == "VioletRed4") return TraCIColor(139, 34, 82, 255);
if (tkColorName == "wheat") return TraCIColor(245, 222, 179, 255);
if (tkColorName == "wheat1") return TraCIColor(255, 231, 186, 255);
if (tkColorName == "wheat2") return TraCIColor(238, 216, 174, 255);
if (tkColorName == "wheat3") return TraCIColor(205, 186, 150, 255);
if (tkColorName == "wheat4") return TraCIColor(139, 126, 102, 255);
if (tkColorName == "white") return TraCIColor(255, 255, 255, 255);
if (tkColorName == "white smoke") return TraCIColor(245, 245, 245, 255);
if (tkColorName == "WhiteSmoke") return TraCIColor(245, 245, 245, 255);
if (tkColorName == "yellow") return TraCIColor(255, 255, 0, 255);
if (tkColorName == "yellow green") return TraCIColor(154, 205, 50, 255);
if (tkColorName == "yellow1") return TraCIColor(255, 255, 0, 255);
if (tkColorName == "yellow2") return TraCIColor(238, 238, 0, 255);
if (tkColorName == "yellow3") return TraCIColor(205, 205, 0, 255);
if (tkColorName == "yellow4") return TraCIColor(139, 139, 0, 255);
if (tkColorName == "YellowGreen") return TraCIColor(154, 205, 50, 255);
throw cRuntimeError("unknown color name: %s", tkColorName.c_str());
}
| 56,742 | 70.735777 | 87 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIColor.h | //
// Copyright (C) 2006-2011 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
namespace veins {
/**
* TraCI compatible color container
*/
class VEINS_API TraCIColor {
public:
TraCIColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha);
static TraCIColor fromTkColor(std::string tkColorName);
public:
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t alpha;
};
} // namespace veins
| 1,293 | 27.755556 | 76 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCICommandInterface.cc | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <stdlib.h>
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/ParBuffer.h"
#ifdef _WIN32
#define realpath(N, R) _fullpath((R), (N), _MAX_PATH)
#endif /* _WIN32 */
using namespace veins::TraCIConstants;
namespace veins {
const std::map<uint32_t, TraCICommandInterface::VersionConfig> TraCICommandInterface::versionConfigs = {
{20, {20, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}},
{19, {19, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}},
{18, {18, TYPE_DOUBLE, TYPE_POLYGON, VAR_TIME}},
{17, {17, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}},
{16, {16, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}},
{15, {15, TYPE_INTEGER, TYPE_BOUNDINGBOX, VAR_TIME_STEP}},
};
TraCICommandInterface::TraCICommandInterface(cComponent* owner, TraCIConnection& c, bool ignoreGuiCommands)
: HasLogProxy(owner)
, connection(c)
, ignoreGuiCommands(ignoreGuiCommands)
{
}
bool TraCICommandInterface::isIgnoringGuiCommands()
{
return ignoreGuiCommands;
}
std::pair<uint32_t, std::string> TraCICommandInterface::getVersion()
{
TraCIConnection::Result result;
TraCIBuffer buf = connection.query(CMD_GETVERSION, TraCIBuffer(), &result);
if (!result.success) {
ASSERT(buf.eof());
return std::pair<uint32_t, std::string>(0, "(unknown)");
}
uint8_t cmdLength;
buf >> cmdLength;
uint8_t commandResp;
buf >> commandResp;
ASSERT(commandResp == CMD_GETVERSION);
uint32_t apiVersion;
buf >> apiVersion;
std::string serverVersion;
buf >> serverVersion;
ASSERT(buf.eof());
return std::pair<uint32_t, std::string>(apiVersion, serverVersion);
}
void TraCICommandInterface::setApiVersion(uint32_t apiVersion)
{
try {
versionConfig = versionConfigs.at(apiVersion);
TraCIBuffer::setTimeType(versionConfig.timeType);
}
catch (std::out_of_range const& exc) {
throw cRuntimeError(std::string("TraCI server reports unsupported TraCI API version: " + std::to_string(apiVersion) + ". We recommend using Sumo version 1.0.1 or 0.32.0").c_str());
}
}
std::pair<TraCICoord, TraCICoord> TraCICommandInterface::initNetworkBoundaries(int margin)
{
// query road network boundaries
TraCIBuffer buf = connection.query(CMD_GET_SIM_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_NET_BOUNDING_BOX) << std::string("sim0"));
uint8_t cmdLength_resp;
buf >> cmdLength_resp;
uint8_t commandId_resp;
buf >> commandId_resp;
ASSERT(commandId_resp == RESPONSE_GET_SIM_VARIABLE);
uint8_t variableId_resp;
buf >> variableId_resp;
ASSERT(variableId_resp == VAR_NET_BOUNDING_BOX);
std::string simId;
buf >> simId;
uint8_t typeId_resp;
buf >> typeId_resp;
ASSERT(typeId_resp == getNetBoundaryType());
if (getNetBoundaryType() == TYPE_POLYGON) {
// Polygons can have an arbitrary number of tuples, so check that it is actually 2
uint8_t npoints;
buf >> npoints;
ASSERT(npoints == 2);
}
double x1;
buf >> x1;
double y1;
buf >> y1;
double x2;
buf >> x2;
double y2;
buf >> y2;
ASSERT(buf.eof());
EV_DEBUG << "TraCI reports network boundaries (" << x1 << ", " << y1 << ")-(" << x2 << ", " << y2 << ")" << endl;
TraCICoord nb1(x1, y1);
TraCICoord nb2(x2, y2);
connection.setNetbounds(nb1, nb2, margin);
return {nb1, nb2};
}
void TraCICommandInterface::Vehicle::setSpeedMode(int32_t bitset)
{
uint8_t variableId = VAR_SPEEDSETMODE;
uint8_t variableType = TYPE_INTEGER;
TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << bitset);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::setSpeed(double speed)
{
uint8_t variableId = VAR_SPEED;
uint8_t variableType = TYPE_DOUBLE;
TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << speed);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::setMaxSpeed(double speed)
{
uint8_t variableId = VAR_MAXSPEED;
uint8_t variableType = TYPE_DOUBLE;
TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << speed);
ASSERT(buf.eof());
}
TraCIColor TraCICommandInterface::Vehicle::getColor()
{
TraCIColor res(0, 0, 0, 0);
TraCIBuffer p;
p << static_cast<uint8_t>(VAR_COLOR);
p << nodeId;
TraCIBuffer buf = connection->query(CMD_GET_VEHICLE_VARIABLE, p);
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
uint8_t responseId = RESPONSE_GET_VEHICLE_VARIABLE;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
uint8_t variableId = VAR_COLOR;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
std::string objectId = nodeId;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
uint8_t resultTypeId = TYPE_COLOR;
ASSERT(resType_r == resultTypeId);
buf >> res.red;
buf >> res.green;
buf >> res.blue;
buf >> res.alpha;
ASSERT(buf.eof());
return res;
}
void TraCICommandInterface::Vehicle::setColor(const TraCIColor& color)
{
TraCIBuffer p;
p << static_cast<uint8_t>(VAR_COLOR);
p << nodeId;
p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha;
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, p);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::slowDown(double speed, simtime_t time)
{
uint8_t variableId = CMD_SLOWDOWN;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 2;
uint8_t speedType = TYPE_DOUBLE;
uint8_t durationType = traci->getTimeType();
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << speedType << speed << durationType << time);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::newRoute(std::string roadId)
{
uint8_t variableId = LANE_EDGE_ID;
uint8_t variableType = TYPE_STRING;
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << roadId);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::setParking()
{
throw cRuntimeError("TraCICommandInterface::Vehicle::setParking is non-functional as of SUMO 1.0.0");
}
std::list<std::string> TraCICommandInterface::getVehicleTypeIds()
{
return genericGetStringList(CMD_GET_VEHICLETYPE_VARIABLE, "", ID_LIST, RESPONSE_GET_VEHICLETYPE_VARIABLE);
}
std::list<std::string> TraCICommandInterface::getRouteIds()
{
return genericGetStringList(CMD_GET_ROUTE_VARIABLE, "", ID_LIST, RESPONSE_GET_ROUTE_VARIABLE);
}
std::list<std::string> TraCICommandInterface::getRoadIds()
{
return genericGetStringList(CMD_GET_EDGE_VARIABLE, "", ID_LIST, RESPONSE_GET_EDGE_VARIABLE);
}
double TraCICommandInterface::Road::getCurrentTravelTime()
{
return traci->genericGetDouble(CMD_GET_EDGE_VARIABLE, roadId, VAR_CURRENT_TRAVELTIME, RESPONSE_GET_EDGE_VARIABLE);
}
double TraCICommandInterface::Road::getMeanSpeed()
{
return traci->genericGetDouble(CMD_GET_EDGE_VARIABLE, roadId, LAST_STEP_MEAN_SPEED, RESPONSE_GET_EDGE_VARIABLE);
}
std::string TraCICommandInterface::Vehicle::getRoadId()
{
return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ROAD_ID, RESPONSE_GET_VEHICLE_VARIABLE);
}
std::string TraCICommandInterface::Vehicle::getLaneId()
{
return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANE_ID, RESPONSE_GET_VEHICLE_VARIABLE);
}
int32_t TraCICommandInterface::Vehicle::getLaneIndex()
{
return traci->genericGetInt(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANE_INDEX, RESPONSE_GET_VEHICLE_VARIABLE);
}
std::string TraCICommandInterface::Vehicle::getTypeId()
{
return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_TYPE, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getMaxSpeed()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_MAXSPEED, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getLanePosition()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LANEPOSITION, RESPONSE_GET_VEHICLE_VARIABLE);
}
std::list<std::string> TraCICommandInterface::Vehicle::getPlannedRoadIds()
{
return traci->genericGetStringList(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_EDGES, RESPONSE_GET_VEHICLE_VARIABLE);
}
std::string TraCICommandInterface::Vehicle::getRouteId()
{
return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ROUTE_ID, RESPONSE_GET_VEHICLE_VARIABLE);
}
std::list<std::string> TraCICommandInterface::Route::getRoadIds()
{
return traci->genericGetStringList(CMD_GET_ROUTE_VARIABLE, routeId, VAR_EDGES, RESPONSE_GET_ROUTE_VARIABLE);
}
void TraCICommandInterface::Vehicle::changeRoute(std::string roadId, simtime_t travelTime)
{
if (travelTime >= 0) {
uint8_t variableId = VAR_EDGE_TRAVELTIME;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 2;
uint8_t edgeIdT = TYPE_STRING;
std::string edgeId = roadId;
uint8_t newTimeT = TYPE_DOUBLE; // has always been seconds as double
double newTime = travelTime.dbl();
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId << newTimeT << newTime);
ASSERT(buf.eof());
}
else {
uint8_t variableId = VAR_EDGE_TRAVELTIME;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 1;
uint8_t edgeIdT = TYPE_STRING;
std::string edgeId = roadId;
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId);
ASSERT(buf.eof());
}
{
uint8_t variableId = CMD_REROUTE_TRAVELTIME;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 0;
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count);
ASSERT(buf.eof());
}
}
double TraCICommandInterface::Vehicle::getLength()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_LENGTH, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getWidth()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WIDTH, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getHeight()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_HEIGHT, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getAccel()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ACCEL, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getDeccel()
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_DECEL, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getCO2Emissions() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_CO2EMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getCOEmissions() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_COEMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getHCEmissions() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_HCEMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getPMxEmissions() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_PMXEMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getNOxEmissions() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_NOXEMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getFuelConsumption() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_FUELCONSUMPTION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getNoiseEmission() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_NOISEEMISSION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getElectricityConsumption() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_ELECTRICITYCONSUMPTION, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getWaitingTime() const
{
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WAITING_TIME, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::Vehicle::getAccumulatedWaitingTime() const
{
const auto apiVersion = traci->versionConfig.version;
if (apiVersion <= 15) {
throw cRuntimeError("TraCICommandInterface::Vehicle::getAccumulatedWaitingTime requires SUMO 0.31.0 or newer");
}
return traci->genericGetDouble(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_WAITING_TIME_ACCUMULATED, RESPONSE_GET_VEHICLE_VARIABLE);
}
double TraCICommandInterface::getDistance(const Coord& p1, const Coord& p2, bool returnDrivingDistance)
{
uint8_t variable = DISTANCE_REQUEST;
std::string simId = "sim0";
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 3;
uint8_t dType = static_cast<uint8_t>(returnDrivingDistance ? REQUEST_DRIVINGDIST : REQUEST_AIRDIST);
// query road network boundaries
TraCIBuffer buf = connection.query(CMD_GET_SIM_VARIABLE, TraCIBuffer() << variable << simId << variableType << count << connection.omnet2traci(p1) << connection.omnet2traci(p2) << dType);
uint8_t cmdLength_resp;
buf >> cmdLength_resp;
uint8_t commandId_resp;
buf >> commandId_resp;
ASSERT(commandId_resp == RESPONSE_GET_SIM_VARIABLE);
uint8_t variableId_resp;
buf >> variableId_resp;
ASSERT(variableId_resp == variable);
std::string simId_resp;
buf >> simId_resp;
ASSERT(simId_resp == simId);
uint8_t typeId_resp;
buf >> typeId_resp;
ASSERT(typeId_resp == TYPE_DOUBLE);
double distance;
buf >> distance;
ASSERT(buf.eof());
return distance;
}
void TraCICommandInterface::Vehicle::stopAt(std::string roadId, double pos, uint8_t laneid, double radius, simtime_t waittime)
{
uint8_t variableId = CMD_STOP;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 4;
uint8_t edgeIdT = TYPE_STRING;
std::string edgeId = roadId;
uint8_t stopPosT = TYPE_DOUBLE;
double stopPos = pos;
uint8_t stopLaneT = TYPE_BYTE;
uint8_t stopLane = laneid;
uint8_t durationT = traci->getTimeType();
simtime_t duration = waittime;
TraCIBuffer buf = connection->query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << nodeId << variableType << count << edgeIdT << edgeId << stopPosT << stopPos << stopLaneT << stopLane << durationT << duration);
ASSERT(buf.eof());
}
std::list<std::string> TraCICommandInterface::getTrafficlightIds()
{
return genericGetStringList(CMD_GET_TL_VARIABLE, "", ID_LIST, RESPONSE_GET_TL_VARIABLE);
}
std::string TraCICommandInterface::Trafficlight::getCurrentState() const
{
return traci->genericGetString(CMD_GET_TL_VARIABLE, trafficLightId, TL_RED_YELLOW_GREEN_STATE, RESPONSE_GET_TL_VARIABLE);
}
simtime_t TraCICommandInterface::Trafficlight::getDefaultCurrentPhaseDuration() const
{
return traci->genericGetTime(CMD_GET_TL_VARIABLE, trafficLightId, TL_PHASE_DURATION, RESPONSE_GET_TL_VARIABLE);
}
std::list<std::string> TraCICommandInterface::Trafficlight::getControlledLanes() const
{
return traci->genericGetStringList(CMD_GET_TL_VARIABLE, trafficLightId, TL_CONTROLLED_LANES, RESPONSE_GET_TL_VARIABLE);
}
std::list<std::list<TraCITrafficLightLink>> TraCICommandInterface::Trafficlight::getControlledLinks() const
{
uint8_t resultTypeId = TYPE_COMPOUND;
uint8_t commandId = CMD_GET_TL_VARIABLE;
uint8_t variableId = TL_CONTROLLED_LINKS;
std::string objectId = trafficLightId;
uint8_t responseId = RESPONSE_GET_TL_VARIABLE;
TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId);
// generic header
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
int32_t compoundSize;
buf >> compoundSize; // nr of fields in the compound
int32_t nrOfSignals = buf.readTypeChecked<int32_t>(TYPE_INTEGER);
std::list<std::list<TraCITrafficLightLink>> controlledLinks;
for (int32_t i = 0; i < nrOfSignals; ++i) {
int32_t nrOfLinks = buf.readTypeChecked<int32_t>(TYPE_INTEGER);
std::list<TraCITrafficLightLink> linksOfSignal;
uint8_t stringListType;
buf >> stringListType;
ASSERT(stringListType == static_cast<uint8_t>(TYPE_STRINGLIST));
for (int32_t j = 0; j < nrOfLinks; ++j) {
int32_t stringCount;
buf >> stringCount;
ASSERT(stringCount == 3);
TraCITrafficLightLink link;
buf >> link.incoming;
buf >> link.outgoing;
buf >> link.internal;
linksOfSignal.push_back(link);
}
controlledLinks.push_back(linksOfSignal);
}
return controlledLinks;
}
int32_t TraCICommandInterface::Trafficlight::getCurrentPhaseIndex() const
{
return traci->genericGetInt(CMD_GET_TL_VARIABLE, trafficLightId, TL_CURRENT_PHASE, RESPONSE_GET_TL_VARIABLE);
}
std::string TraCICommandInterface::Trafficlight::getCurrentProgramID() const
{
return traci->genericGetString(CMD_GET_TL_VARIABLE, trafficLightId, TL_CURRENT_PROGRAM, RESPONSE_GET_TL_VARIABLE);
}
TraCITrafficLightProgram TraCICommandInterface::Trafficlight::getProgramDefinition() const
{
uint8_t resultTypeId = TYPE_COMPOUND;
TraCITrafficLightProgram program(trafficLightId);
const auto apiVersion = traci->versionConfig.version;
if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17 || apiVersion == 18) {
uint8_t commandId = CMD_GET_TL_VARIABLE;
uint8_t variableId = TL_COMPLETE_DEFINITION_RYG;
std::string objectId = trafficLightId;
uint8_t responseId = RESPONSE_GET_TL_VARIABLE;
TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId);
// generic header
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
int32_t compoundSize;
buf >> compoundSize; // nr of fields in the compound
int32_t nrOfLogics = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // nr of logics in the compound
for (int32_t i = 0; i < nrOfLogics; ++i) {
TraCITrafficLightProgram::Logic logic;
logic.id = buf.readTypeChecked<std::string>(TYPE_STRING); // program ID
logic.type = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // (sub)type - currently just a 0
logic.parameter = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // (sub)parameter - currently just a 0
logic.currentPhase = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // phase index
int32_t nrOfPhases = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // number of phases in this program
for (int32_t j = 0; j < nrOfPhases; ++j) {
TraCITrafficLightProgram::Phase phase;
phase.duration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // default duration of phase
phase.minDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // minimum duration of phase
phase.maxDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // maximum duration of phase
phase.state = buf.readTypeChecked<std::string>(TYPE_STRING); // phase definition (like "[ryg]*")
logic.phases.push_back(phase);
}
program.addLogic(logic);
}
}
else if (apiVersion == 19 || apiVersion == 20) {
uint8_t commandId = CMD_GET_TL_VARIABLE;
uint8_t variableId = TL_COMPLETE_DEFINITION_RYG;
std::string objectId = trafficLightId;
uint8_t responseId = RESPONSE_GET_TL_VARIABLE;
TraCIBuffer buf = connection->query(commandId, TraCIBuffer() << variableId << objectId);
// generic header
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
int32_t nrOfLogics = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // nr of logics in the compound
for (int32_t i = 0; i < nrOfLogics; ++i) {
int32_t nrOfComps = buf.readTypeChecked<int32_t>(TYPE_COMPOUND);
ASSERT(nrOfComps == 5);
TraCITrafficLightProgram::Logic logic;
logic.id = buf.readTypeChecked<std::string>(TYPE_STRING); // program ID
logic.type = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // (sub)type - currently just a 0
logic.currentPhase = buf.readTypeChecked<int32_t>(TYPE_INTEGER); // phase index
int32_t nrOfPhases = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // number of phases in this program
for (int32_t j = 0; j < nrOfPhases; ++j) {
TraCITrafficLightProgram::Phase phase;
int32_t nrOfComps = buf.readTypeChecked<int32_t>(TYPE_COMPOUND);
ASSERT((apiVersion == 19 && nrOfComps == 5) || (apiVersion == 20 && nrOfComps == 6));
phase.duration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // default duration of phase
phase.state = buf.readTypeChecked<std::string>(TYPE_STRING); // phase definition (like "[ryg]*")
phase.minDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // minimum duration of phase
phase.maxDuration = buf.readTypeChecked<simtime_t>(traci->getTimeType()); // maximum duration of phase
if (apiVersion <= 19) {
phase.next = {buf.readTypeChecked<int32_t>(TYPE_INTEGER)};
}
else {
int32_t nextCount = buf.readTypeChecked<int32_t>(TYPE_COMPOUND);
phase.next = {};
for (int32_t k = 0; k < nextCount; ++k) {
phase.next.push_back(buf.readTypeChecked<int32_t>(TYPE_INTEGER));
}
}
if (apiVersion == 20) {
phase.name = buf.readTypeChecked<std::string>(TYPE_STRING);
}
logic.phases.push_back(phase);
}
int32_t nrOfSubpars = buf.readTypeChecked<int32_t>(TYPE_COMPOUND); // nr of subparameters
for (int32_t j = 0; j < nrOfSubpars; ++j) {
uint8_t stringListType;
buf >> stringListType;
ASSERT(stringListType == static_cast<uint8_t>(TYPE_STRINGLIST));
std::string s1;
buf >> s1; // discard
std::string s2;
buf >> s2; // discard
}
program.addLogic(logic);
}
}
else {
throw cRuntimeError("Invalid API version used, check your code.");
}
return program;
}
simtime_t TraCICommandInterface::Trafficlight::getAssumedNextSwitchTime() const
{
return traci->genericGetTime(CMD_GET_TL_VARIABLE, trafficLightId, TL_NEXT_SWITCH, RESPONSE_GET_TL_VARIABLE);
}
void TraCICommandInterface::Trafficlight::setState(std::string state)
{
TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_RED_YELLOW_GREEN_STATE) << trafficLightId << static_cast<uint8_t>(TYPE_STRING) << state);
ASSERT(buf.eof());
}
void TraCICommandInterface::Trafficlight::setPhaseDuration(simtime_t duration)
{
TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PHASE_DURATION) << trafficLightId << static_cast<uint8_t>(traci->getTimeType()) << duration);
ASSERT(buf.eof());
}
void TraCICommandInterface::Trafficlight::setProgramDefinition(TraCITrafficLightProgram::Logic logic, int32_t logicNr)
{
TraCIBuffer inbuf;
const auto apiVersion = traci->versionConfig.version;
if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17 || apiVersion == 18) {
inbuf << static_cast<uint8_t>(TL_COMPLETE_PROGRAM_RYG);
inbuf << trafficLightId;
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << logicNr;
inbuf << static_cast<uint8_t>(TYPE_STRING);
inbuf << logic.id;
inbuf << static_cast<uint8_t>(TYPE_INTEGER); // (sub)type - currently unused
inbuf << logic.type;
inbuf << static_cast<uint8_t>(TYPE_COMPOUND); // (sub)parameter - currently unused
inbuf << logic.parameter;
inbuf << static_cast<uint8_t>(TYPE_INTEGER);
inbuf << logic.currentPhase;
inbuf << static_cast<uint8_t>(TYPE_INTEGER);
inbuf << static_cast<int32_t>(logic.phases.size());
for (uint32_t i = 0; i < logic.phases.size(); ++i) {
TraCITrafficLightProgram::Phase& phase = logic.phases[i];
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.duration;
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.minDuration;
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.maxDuration;
inbuf << static_cast<uint8_t>(TYPE_STRING);
inbuf << phase.state;
}
}
else if (apiVersion == 19 || apiVersion == 20) {
inbuf << static_cast<uint8_t>(TL_COMPLETE_PROGRAM_RYG);
inbuf << trafficLightId;
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << 5;
inbuf << static_cast<uint8_t>(TYPE_STRING);
inbuf << logic.id;
inbuf << static_cast<uint8_t>(TYPE_INTEGER); // (sub)type - currently unused
inbuf << logic.type;
inbuf << static_cast<uint8_t>(TYPE_INTEGER);
inbuf << logic.currentPhase;
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << static_cast<int32_t>(logic.phases.size());
for (uint32_t i = 0; i < logic.phases.size(); ++i) {
TraCITrafficLightProgram::Phase& phase = logic.phases[i];
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << int32_t((apiVersion == 19) ? 5 : 6);
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.duration;
inbuf << static_cast<uint8_t>(TYPE_STRING);
inbuf << phase.state;
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.minDuration;
inbuf << static_cast<uint8_t>(traci->getTimeType());
inbuf << phase.maxDuration;
if (apiVersion <= 19) {
inbuf << static_cast<uint8_t>(TYPE_INTEGER);
if (phase.next.size() == 0) {
inbuf << static_cast<int32_t>(0);
}
else if (phase.next.size() == 1) {
inbuf << static_cast<int32_t>(phase.next[0]);
}
else {
throw cRuntimeError("Setting multiple phase.next requires a newer version of SUMO");
}
}
else {
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << static_cast<int32_t>(phase.next.size());
for (int32_t next : phase.next) {
inbuf << static_cast<uint8_t>(TYPE_INTEGER);
inbuf << next;
}
}
if (apiVersion == 20) {
inbuf << static_cast<uint8_t>(TYPE_STRING);
inbuf << phase.name;
}
}
// no subparameters
inbuf << static_cast<uint8_t>(TYPE_COMPOUND);
inbuf << int32_t(0);
}
else {
throw cRuntimeError("Invalid API version used, check your code.");
}
TraCIBuffer obuf = connection->query(CMD_SET_TL_VARIABLE, inbuf);
ASSERT(obuf.eof());
}
void TraCICommandInterface::Trafficlight::setProgram(std::string program)
{
TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PROGRAM) << trafficLightId << static_cast<uint8_t>(TYPE_STRING) << program);
ASSERT(buf.eof());
}
void TraCICommandInterface::Trafficlight::setPhaseIndex(int32_t index)
{
TraCIBuffer buf = connection->query(CMD_SET_TL_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(TL_PHASE_INDEX) << trafficLightId << static_cast<uint8_t>(TYPE_INTEGER) << index);
ASSERT(buf.eof());
}
std::list<std::string> TraCICommandInterface::getPolygonIds()
{
return genericGetStringList(CMD_GET_POLYGON_VARIABLE, "", ID_LIST, RESPONSE_GET_POLYGON_VARIABLE);
}
std::string TraCICommandInterface::Polygon::getTypeId()
{
return traci->genericGetString(CMD_GET_POLYGON_VARIABLE, polyId, VAR_TYPE, RESPONSE_GET_POLYGON_VARIABLE);
}
std::list<Coord> TraCICommandInterface::Polygon::getShape()
{
return traci->genericGetCoordList(CMD_GET_POLYGON_VARIABLE, polyId, VAR_SHAPE, RESPONSE_GET_POLYGON_VARIABLE);
}
void TraCICommandInterface::Polygon::setShape(const std::list<Coord>& points)
{
TraCIBuffer buf;
uint8_t count = static_cast<uint8_t>(points.size());
buf << static_cast<uint8_t>(VAR_SHAPE) << polyId << static_cast<uint8_t>(TYPE_POLYGON) << count;
for (std::list<Coord>::const_iterator i = points.begin(); i != points.end(); ++i) {
const TraCICoord& pos = connection->omnet2traci(*i);
buf << static_cast<double>(pos.x) << static_cast<double>(pos.y);
}
TraCIBuffer obuf = connection->query(CMD_SET_POLYGON_VARIABLE, buf);
ASSERT(obuf.eof());
}
void TraCICommandInterface::addPolygon(std::string polyId, std::string polyType, const TraCIColor& color, bool filled, int32_t layer, const std::list<Coord>& points)
{
TraCIBuffer p;
p << static_cast<uint8_t>(ADD) << polyId;
p << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(5);
p << static_cast<uint8_t>(TYPE_STRING) << polyType;
p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha;
p << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(filled);
p << static_cast<uint8_t>(TYPE_INTEGER) << layer;
p << static_cast<uint8_t>(TYPE_POLYGON) << static_cast<uint8_t>(points.size());
for (std::list<Coord>::const_iterator i = points.begin(); i != points.end(); ++i) {
const TraCICoord& pos = connection.omnet2traci(*i);
p << static_cast<double>(pos.x) << static_cast<double>(pos.y);
}
TraCIBuffer buf = connection.query(CMD_SET_POLYGON_VARIABLE, p);
ASSERT(buf.eof());
}
void TraCICommandInterface::Polygon::remove(int32_t layer)
{
TraCIBuffer p;
p << static_cast<uint8_t>(REMOVE) << polyId;
p << static_cast<uint8_t>(TYPE_INTEGER) << layer;
TraCIBuffer buf = connection->query(CMD_SET_POLYGON_VARIABLE, p);
ASSERT(buf.eof());
}
std::list<std::string> TraCICommandInterface::getPoiIds()
{
return genericGetStringList(CMD_GET_POI_VARIABLE, "", ID_LIST, RESPONSE_GET_POI_VARIABLE);
}
void TraCICommandInterface::addPoi(std::string poiId, std::string poiType, const TraCIColor& color, int32_t layer, const Coord& pos_)
{
TraCIBuffer p;
TraCICoord pos = connection.omnet2traci(pos_);
p << static_cast<uint8_t>(ADD) << poiId;
p << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(4);
p << static_cast<uint8_t>(TYPE_STRING) << poiType;
p << static_cast<uint8_t>(TYPE_COLOR) << color.red << color.green << color.blue << color.alpha;
p << static_cast<uint8_t>(TYPE_INTEGER) << layer;
p << pos;
TraCIBuffer buf = connection.query(CMD_SET_POI_VARIABLE, p);
ASSERT(buf.eof());
}
void TraCICommandInterface::Poi::remove(int32_t layer)
{
TraCIBuffer p;
p << static_cast<uint8_t>(REMOVE) << poiId;
p << static_cast<uint8_t>(TYPE_INTEGER) << layer;
TraCIBuffer buf = connection->query(CMD_SET_POI_VARIABLE, p);
ASSERT(buf.eof());
}
std::list<std::string> TraCICommandInterface::getLaneIds()
{
return genericGetStringList(CMD_GET_LANE_VARIABLE, "", ID_LIST, RESPONSE_GET_LANE_VARIABLE);
}
std::list<Coord> TraCICommandInterface::Lane::getShape()
{
return traci->genericGetCoordList(CMD_GET_LANE_VARIABLE, laneId, VAR_SHAPE, RESPONSE_GET_LANE_VARIABLE);
}
std::string TraCICommandInterface::Lane::getRoadId()
{
return traci->genericGetString(CMD_GET_LANE_VARIABLE, laneId, LANE_EDGE_ID, RESPONSE_GET_LANE_VARIABLE);
}
double TraCICommandInterface::Lane::getLength()
{
return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, VAR_LENGTH, RESPONSE_GET_LANE_VARIABLE);
}
double TraCICommandInterface::Lane::getMaxSpeed()
{
return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, VAR_MAXSPEED, RESPONSE_GET_LANE_VARIABLE);
}
double TraCICommandInterface::Lane::getMeanSpeed()
{
return traci->genericGetDouble(CMD_GET_LANE_VARIABLE, laneId, LAST_STEP_MEAN_SPEED, RESPONSE_GET_LANE_VARIABLE);
}
std::list<std::string> TraCICommandInterface::getLaneAreaDetectorIds()
{
return genericGetStringList(CMD_GET_LANEAREA_VARIABLE, "", ID_LIST, RESPONSE_GET_LANEAREA_VARIABLE);
}
int TraCICommandInterface::LaneAreaDetector::getLastStepVehicleNumber()
{
return traci->genericGetInt(CMD_GET_LANEAREA_VARIABLE, laneAreaDetectorId, LAST_STEP_VEHICLE_NUMBER, RESPONSE_GET_LANEAREA_VARIABLE);
}
std::list<std::string> TraCICommandInterface::getJunctionIds()
{
return genericGetStringList(CMD_GET_JUNCTION_VARIABLE, "", ID_LIST, RESPONSE_GET_JUNCTION_VARIABLE);
}
Coord TraCICommandInterface::Junction::getPosition()
{
return traci->genericGetCoord(CMD_GET_JUNCTION_VARIABLE, junctionId, VAR_POSITION, RESPONSE_GET_JUNCTION_VARIABLE);
}
bool TraCICommandInterface::addVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, simtime_t emitTime_st, double emitPosition, double emitSpeed, int8_t emitLane)
{
TraCIConnection::Result result;
uint8_t variableId = ADD;
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 6;
int32_t emitTime = (emitTime_st < 0) ? round(emitTime_st.dbl()) : (floor(emitTime_st.dbl() * 1000));
TraCIBuffer buf = connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << variableId << vehicleId << variableType << count << (uint8_t) TYPE_STRING << vehicleTypeId << (uint8_t) TYPE_STRING << routeId << (uint8_t) TYPE_INTEGER << emitTime << (uint8_t) TYPE_DOUBLE << emitPosition << (uint8_t) TYPE_DOUBLE << emitSpeed << (uint8_t) TYPE_BYTE << emitLane, &result);
ASSERT(buf.eof());
return result.success;
}
bool TraCICommandInterface::Vehicle::changeVehicleRoute(const std::list<std::string>& edges)
{
if (getRoadId().find(':') != std::string::npos) return false;
if (edges.front().compare(getRoadId()) != 0) return false;
uint8_t variableId = VAR_ROUTE;
uint8_t variableType = TYPE_STRINGLIST;
TraCIBuffer buf;
buf << variableId << nodeId << variableType;
int32_t numElem = edges.size();
buf << numElem;
for (std::list<std::string>::const_iterator i = edges.begin(); i != edges.end(); ++i) {
buf << static_cast<std::string>(*i);
}
TraCIBuffer obuf = connection->query(CMD_SET_VEHICLE_VARIABLE, buf);
ASSERT(obuf.eof());
return true;
}
void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, int value)
{
std::stringstream strValue;
strValue << value;
setParameter(parameter, strValue.str());
}
void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, double value)
{
std::stringstream strValue;
strValue << value;
setParameter(parameter, strValue.str());
}
void TraCICommandInterface::Vehicle::setParameter(const std::string& parameter, const std::string& value)
{
static int32_t nParameters = 2;
TraCIBuffer buf = traci->connection.query(CMD_SET_VEHICLE_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_PARAMETER) << nodeId << static_cast<uint8_t>(TYPE_COMPOUND) << nParameters << static_cast<uint8_t>(TYPE_STRING) << parameter << static_cast<uint8_t>(TYPE_STRING) << value);
ASSERT(buf.eof());
}
void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, int& value)
{
std::string v;
getParameter(parameter, v);
ParBuffer buf(v);
buf >> value;
}
void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, double& value)
{
std::string v;
getParameter(parameter, v);
ParBuffer buf(v);
buf >> value;
}
void TraCICommandInterface::Vehicle::getParameter(const std::string& parameter, std::string& value)
{
TraCIBuffer response = traci->connection.query(CMD_GET_VEHICLE_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_PARAMETER) << nodeId << static_cast<uint8_t>(TYPE_STRING) << parameter);
uint8_t cmdLength;
response >> cmdLength;
uint8_t responseId;
response >> responseId;
ASSERT(responseId == RESPONSE_GET_VEHICLE_VARIABLE);
uint8_t variable;
response >> variable;
ASSERT(variable == VAR_PARAMETER);
std::string id;
response >> id;
ASSERT(id == nodeId);
uint8_t type;
response >> type;
ASSERT(type == TYPE_STRING);
response >> value;
}
std::pair<double, double> TraCICommandInterface::getLonLat(const Coord& coord)
{
TraCIBuffer request;
request << static_cast<uint8_t>(POSITION_CONVERSION) << std::string("sim0") << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(2) << connection.omnet2traci(coord) << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(POSITION_LON_LAT);
TraCIBuffer response = connection.query(CMD_GET_SIM_VARIABLE, request);
uint8_t cmdLength;
response >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
response >> cmdLengthX;
}
uint8_t responseId;
response >> responseId;
ASSERT(responseId == RESPONSE_GET_SIM_VARIABLE);
uint8_t variable;
response >> variable;
ASSERT(variable == POSITION_CONVERSION);
std::string id;
response >> id;
uint8_t convPosType;
response >> convPosType;
ASSERT(convPosType == POSITION_LON_LAT);
double convPosLon;
response >> convPosLon;
double convPosLat;
response >> convPosLat;
return std::make_pair(convPosLon, convPosLat);
}
std::tuple<std::string, double, uint8_t> TraCICommandInterface::getRoadMapPos(const Coord& coord)
{
TraCIBuffer request;
request << static_cast<uint8_t>(POSITION_CONVERSION) << std::string("sim0") << static_cast<uint8_t>(TYPE_COMPOUND) << static_cast<int32_t>(2) << connection.omnet2traci(coord) << static_cast<uint8_t>(TYPE_UBYTE) << static_cast<uint8_t>(POSITION_ROADMAP);
TraCIBuffer response = connection.query(CMD_GET_SIM_VARIABLE, request);
uint8_t cmdLength;
response >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
response >> cmdLengthX;
}
uint8_t responseId;
response >> responseId;
ASSERT(responseId == RESPONSE_GET_SIM_VARIABLE);
uint8_t variable;
response >> variable;
ASSERT(variable == POSITION_CONVERSION);
std::string id;
response >> id;
uint8_t convPosType;
response >> convPosType;
ASSERT(convPosType == POSITION_ROADMAP);
std::string convRoadId;
response >> convRoadId;
double convPos;
response >> convPos;
uint8_t convLaneId;
response >> convLaneId;
return std::make_tuple(convRoadId, convPos, convLaneId);
}
std::list<std::string> TraCICommandInterface::getGuiViewIds()
{
if (ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return std::list<std::string>();
}
return genericGetStringList(CMD_GET_GUI_VARIABLE, "", ID_LIST, RESPONSE_GET_GUI_VARIABLE);
}
std::string TraCICommandInterface::GuiView::getScheme()
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return std::string();
}
return traci->genericGetString(CMD_GET_GUI_VARIABLE, viewId, VAR_VIEW_SCHEMA, RESPONSE_GET_GUI_VARIABLE);
}
void TraCICommandInterface::GuiView::setScheme(std::string name)
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return;
}
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_SCHEMA) << viewId << static_cast<uint8_t>(TYPE_STRING) << name);
ASSERT(buf.eof());
}
double TraCICommandInterface::GuiView::getZoom()
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return 0;
}
return traci->genericGetDouble(CMD_GET_GUI_VARIABLE, viewId, VAR_VIEW_ZOOM, RESPONSE_GET_GUI_VARIABLE);
}
void TraCICommandInterface::GuiView::setZoom(double zoom)
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return;
}
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_ZOOM) << viewId << static_cast<uint8_t>(TYPE_DOUBLE) << zoom);
ASSERT(buf.eof());
}
void TraCICommandInterface::GuiView::setBoundary(Coord p1_, Coord p2_)
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return;
}
TraCICoord p1 = connection->omnet2traci(p1_);
TraCICoord p2 = connection->omnet2traci(p2_);
if (traci->getNetBoundaryType() == TYPE_POLYGON) {
uint8_t count = 2;
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_BOUNDARY) << viewId << static_cast<uint8_t>(TYPE_POLYGON) << count << p1.x << p1.y << p2.x << p2.y);
ASSERT(buf.eof());
}
else {
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_VIEW_BOUNDARY) << viewId << static_cast<uint8_t>(TYPE_BOUNDINGBOX) << p1.x << p1.y << p2.x << p2.y);
ASSERT(buf.eof());
}
}
void TraCICommandInterface::GuiView::takeScreenshot(std::string filename, int32_t width, int32_t height)
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return;
}
if (filename == "") {
// get absolute path of results/ directory
const char* myResultsDir = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RESULTDIR);
char* s = realpath(myResultsDir, nullptr);
std::string absolutePath = s;
free(s);
// get run id
const char* myRunID = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNID);
// build filename from this
char ss[512];
snprintf(ss, sizeof(ss), "%s/screenshot-%s-@%08.2f.png", absolutePath.c_str(), myRunID, simTime().dbl());
filename = ss;
}
const auto apiVersion = traci->versionConfig.version;
if (apiVersion == 15 || apiVersion == 16 || apiVersion == 17) {
uint8_t variableType = TYPE_COMPOUND;
int32_t count = 3;
uint8_t filenameType = TYPE_STRING;
uint8_t widthType = TYPE_INTEGER;
uint8_t heightType = TYPE_INTEGER;
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_SCREENSHOT) << viewId << variableType << count << filenameType << filename << widthType << width << heightType << height);
ASSERT(buf.eof());
}
else if (apiVersion == 18 || apiVersion == 19 || apiVersion == 20) {
uint8_t filenameType = TYPE_STRING;
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_SCREENSHOT) << viewId << filenameType << filename);
ASSERT(buf.eof());
}
else {
throw cRuntimeError("Invalid API version used, check your code.");
}
}
void TraCICommandInterface::GuiView::trackVehicle(std::string vehicleId)
{
if (traci->ignoreGuiCommands) {
EV_DEBUG << "Ignoring TraCI GUI command (as instructed by ignoreGuiCommands)" << std::endl;
return;
}
TraCIBuffer buf = connection->query(CMD_SET_GUI_VARIABLE, TraCIBuffer() << static_cast<uint8_t>(VAR_TRACK_VEHICLE) << viewId << static_cast<uint8_t>(TYPE_STRING) << vehicleId);
ASSERT(buf.eof());
}
std::string TraCICommandInterface::genericGetString(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = TYPE_STRING;
std::string res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return res;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
buf >> res;
ASSERT(buf.eof());
return res;
}
Coord TraCICommandInterface::genericGetCoord(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = POSITION_2D;
double x;
double y;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return Coord();
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
buf >> x;
buf >> y;
ASSERT(buf.eof());
return connection.traci2omnet(TraCICoord(x, y));
}
double TraCICommandInterface::genericGetDouble(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = TYPE_DOUBLE;
double res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return 0;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
buf >> res;
ASSERT(buf.eof());
return res;
}
simtime_t TraCICommandInterface::genericGetTime(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = getTimeType();
simtime_t res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return res;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
buf >> res;
ASSERT(buf.eof());
return res;
}
int32_t TraCICommandInterface::genericGetInt(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = TYPE_INTEGER;
int32_t res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return 0;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
buf >> res;
ASSERT(buf.eof());
return res;
}
std::list<std::string> TraCICommandInterface::genericGetStringList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = TYPE_STRINGLIST;
std::list<std::string> res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return res;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
uint32_t count;
buf >> count;
for (uint32_t i = 0; i < count; i++) {
std::string id;
buf >> id;
res.push_back(id);
}
ASSERT(buf.eof());
return res;
}
std::list<Coord> TraCICommandInterface::genericGetCoordList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result)
{
uint8_t resultTypeId = TYPE_POLYGON;
std::list<Coord> res;
TraCIBuffer buf = connection.query(commandId, TraCIBuffer() << variableId << objectId, result);
if ((result != nullptr) && (!result->success)) {
return res;
}
uint8_t cmdLength;
buf >> cmdLength;
if (cmdLength == 0) {
uint32_t cmdLengthX;
buf >> cmdLengthX;
}
uint8_t commandId_r;
buf >> commandId_r;
ASSERT(commandId_r == responseId);
uint8_t varId;
buf >> varId;
ASSERT(varId == variableId);
std::string objectId_r;
buf >> objectId_r;
ASSERT(objectId_r == objectId);
uint8_t resType_r;
buf >> resType_r;
ASSERT(resType_r == resultTypeId);
uint8_t count;
buf >> count;
for (uint32_t i = 0; i < count; i++) {
double x;
buf >> x;
double y;
buf >> y;
res.push_back(connection.traci2omnet(TraCICoord(x, y)));
}
ASSERT(buf.eof());
return res;
}
std::string TraCICommandInterface::Vehicle::getVType()
{
return traci->genericGetString(CMD_GET_VEHICLE_VARIABLE, nodeId, VAR_TYPE, RESPONSE_GET_VEHICLE_VARIABLE);
}
} // namespace veins
| 54,381 | 35.254667 | 371 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCICommandInterface.h | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <list>
#include <string>
#include <stdint.h>
#include "veins/modules/mobility/traci/TraCIColor.h"
#include "veins/base/utils/Coord.h"
#include "veins/modules/mobility/traci/TraCICoord.h"
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/world/traci/trafficLight/TraCITrafficLightProgram.h"
#include "veins/modules/utility/HasLogProxy.h"
namespace veins {
class VEINS_API TraCICommandInterface : public HasLogProxy {
public:
TraCICommandInterface(cComponent* owner, TraCIConnection& c, bool ignoreGuiCommands);
bool isIgnoringGuiCommands();
enum DepartTime {
DEPART_TIME_TRIGGERED = -1,
DEPART_TIME_CONTAINER_TRIGGERED = -2,
DEPART_TIME_NOW = -3, // Not yet documented and fully implemented (Sumo 0.30.0)
};
enum DepartSpeed {
DEPART_SPEED_RANDOM = -2,
DEPART_SPEED_MAX = -3,
};
enum DepartPosition {
DEPART_POSITION_RANDOM = -2,
DEPART_POSITION_FREE = -3,
DEPART_POSITION_BASE = -4,
DEPART_POSITION_LAST = -5,
DEPART_POSITION_RANDOM_FREE = -6,
};
enum DepartLane {
DEPART_LANE_RANDOM = -2, // A random lane
DEPART_LANE_FREE = -3, // The least occupied lane
DEPART_LANE_ALLOWED = -4, // The least occupied lane which allows continuation
DEPART_LANE_BEST = -5, // The least occupied of the best lanes
DEPART_LANE_FIRST = -6, // The rightmost valid
};
// General methods that do not deal with a particular object in the simulation
std::pair<uint32_t, std::string> getVersion();
void setApiVersion(uint32_t apiVersion);
std::pair<double, double> getLonLat(const Coord&);
unsigned getApiVersion() const
{
return versionConfig.version;
}
uint8_t getTimeType() const
{
return versionConfig.timeType;
}
uint8_t getNetBoundaryType() const
{
return versionConfig.netBoundaryType;
}
uint8_t getTimeStepCmd() const
{
return versionConfig.timeStepCmd;
}
std::pair<TraCICoord, TraCICoord> initNetworkBoundaries(int margin);
/**
* Convert Cartesian coordination to road map position
* @param coord Cartesian coordination
* @return a tuple of <RoadId, Pos, LaneId> where:
* RoadId identifies a road segment (edge)
* Pos describes the position of the node in longitudinal direction (ranging from 0 to the road's length)
* LaneId identifies the driving lane on the edge.
*/
std::tuple<std::string, double, uint8_t> getRoadMapPos(const Coord& coord);
/**
* Get the distance between two arbitrary positions.
*
* @param position1 OMNeT coordinate of first position
* @param position2 OMNeT coordinate of second position
* @param returnDrivingDistance whether to return the driving distance or the air distance
* @return the distance between the two positions
*/
double getDistance(const Coord& position1, const Coord& position2, bool returnDrivingDistance);
// Vehicle methods
/**
* @brief Adds a vehicle to the simulation.
*
* @param vehicleId The new vehicle's ID.
* @param vehicleTypeId The new vehicle's type identifier.
* @param routeId Identifier of the new vehicle's route.
* @param emitTime_st Time at which to spawn the new vehicle or a value from DepartTime.
* @param emitPosition Position of the new vehicle on its lane. Valid values are between 0 and 1 (start and
* end of edge) and special values from DepartPosition.
* @param emitSpeed Speed in meters per second of the new vehicle. Also accepts special values from DepartSpeed.
* @param emitLane The new vehicle's lane. Special Also accepts special values from DepartLane.
* @return Success indication
*/
bool addVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, simtime_t emitTime_st = DEPART_TIME_TRIGGERED, double emitPosition = DEPART_POSITION_BASE, double emitSpeed = DEPART_SPEED_MAX, int8_t emitLane = DEPART_LANE_BEST);
class VEINS_API Vehicle {
public:
Vehicle(TraCICommandInterface* traci, std::string nodeId)
: traci(traci)
, nodeId(nodeId)
{
connection = &traci->connection;
}
void setSpeedMode(int32_t bitset);
void setSpeed(double speed);
void setMaxSpeed(double speed);
TraCIColor getColor();
void setColor(const TraCIColor& color);
void slowDown(double speed, simtime_t time);
void newRoute(std::string roadId);
void setParking();
std::string getRoadId();
std::string getLaneId();
double getMaxSpeed();
double getLanePosition();
std::list<std::string> getPlannedRoadIds();
std::string getRouteId();
void changeRoute(std::string roadId, simtime_t travelTime);
void stopAt(std::string roadId, double pos, uint8_t laneid, double radius, simtime_t waittime);
int32_t getLaneIndex();
std::string getTypeId();
bool changeVehicleRoute(const std::list<std::string>& roads);
double getLength();
double getWidth();
double getHeight();
double getAccel();
double getDeccel();
void setParameter(const std::string& parameter, int value);
void setParameter(const std::string& parameter, double value);
void setParameter(const std::string& parameter, const std::string& value);
void getParameter(const std::string& parameter, int& value);
void getParameter(const std::string& parameter, double& value);
void getParameter(const std::string& parameter, std::string& value);
/**
* Returns the vehicle type of a vehicle
*/
std::string getVType();
/**
* Get the vehicle's CO2 emissions in mg during this time step.
*
* @return the vehicle's CO2 emissions, -1001 in case of error
*/
double getCO2Emissions() const;
/**
* Get the vehicle's CO emissions in mg during this time step.
*
* @return the vehicle's CO emissions, -1001 in case of error
*/
double getCOEmissions() const;
/**
* Get the vehicle's HC emissions in mg during this time step.
*
* @return the vehicle's HC emissions, -1001 in case of error
*/
double getHCEmissions() const;
/**
* Get the vehicle's PMx emissions in mg during this time step.
*
* @return the vehicle's PMx emissions, -1001 in case of error
*/
double getPMxEmissions() const;
/**
* Get the vehicle's NOx emissions in mg during this time step.
*
* @return the vehicle's NOx emissions, -1001 in case of error
*/
double getNOxEmissions() const;
/**
* Get the vehicle's fuel consumption in ml during this time step.
*
* @return the vehicle's fuel consumption, -1001 in case of error
*/
double getFuelConsumption() const;
/**
* Get the noise generated by the vehicle's in dbA during this time step.
*
* @return the noise, -1001 in case of error
*/
double getNoiseEmission() const;
/**
* Get the vehicle's electricity consumption in kWh during this time step.
*
* @return the vehicle's electricity consumption, -1001 in case of error
*/
double getElectricityConsumption() const;
/**
* Get the vehicle's waiting time in s.
* The waiting time of a vehicle is defined as the time (in seconds) spent with a speed below 0.1m/s since the last time it was faster than 0.1m/s.
* (basically, the waiting time of a vehicle is reset to 0 every time it moves).
* A vehicle that is stopping intentionally with a "stop" command does not accumulate waiting time.
*
* @return the vehicle's waiting time
*/
double getWaitingTime() const;
/**
* Get the vehicle's accumulated waiting time in s within the previous time interval.
* The length of the interval is configurable and 100s per default.
*
* @return the accumulated waiting time
*/
double getAccumulatedWaitingTime() const;
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string nodeId;
};
Vehicle vehicle(std::string nodeId)
{
return Vehicle(this, nodeId);
}
// Road methods
std::list<std::string> getRoadIds();
class VEINS_API Road {
public:
Road(TraCICommandInterface* traci, std::string roadId)
: traci(traci)
, roadId(roadId)
{
connection = &traci->connection;
}
double getCurrentTravelTime();
double getMeanSpeed();
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string roadId;
};
Road road(std::string roadId)
{
return Road(this, roadId);
}
// Lane methods
std::list<std::string> getLaneIds();
class VEINS_API Lane {
public:
Lane(TraCICommandInterface* traci, std::string laneId)
: traci(traci)
, laneId(laneId)
{
connection = &traci->connection;
}
std::list<Coord> getShape();
std::string getRoadId();
double getLength();
double getMaxSpeed();
double getMeanSpeed();
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string laneId;
};
Lane lane(std::string laneId)
{
return Lane(this, laneId);
}
// Trafficlight methods
std::list<std::string> getTrafficlightIds();
class VEINS_API Trafficlight {
public:
Trafficlight(TraCICommandInterface* traci, std::string trafficLightId)
: traci(traci)
, trafficLightId(trafficLightId)
{
connection = &traci->connection;
}
std::string getCurrentState() const;
simtime_t getDefaultCurrentPhaseDuration() const;
std::list<std::string> getControlledLanes() const;
std::list<std::list<TraCITrafficLightLink>> getControlledLinks() const;
int32_t getCurrentPhaseIndex() const;
std::string getCurrentProgramID() const;
TraCITrafficLightProgram getProgramDefinition() const;
simtime_t getAssumedNextSwitchTime() const;
void setProgram(std::string program); /**< set/switch to different program */
void setPhaseIndex(int32_t index); /**< set/switch to different phase within the program */
void setState(std::string state);
void setPhaseDuration(simtime_t duration); /**< set remaining duration of current phase */
void setProgramDefinition(TraCITrafficLightProgram::Logic program, int32_t programNr);
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string trafficLightId;
};
Trafficlight trafficlight(std::string trafficLightId)
{
return Trafficlight(this, trafficLightId);
}
// LaneAreaDetector methods
std::list<std::string> getLaneAreaDetectorIds();
class VEINS_API LaneAreaDetector {
public:
LaneAreaDetector(TraCICommandInterface* traci, std::string laneAreaDetectorId)
: traci(traci)
, laneAreaDetectorId(laneAreaDetectorId)
{
connection = &traci->connection;
}
int getLastStepVehicleNumber();
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string laneAreaDetectorId;
};
LaneAreaDetector laneAreaDetector(std::string laneAreaDetectorId)
{
return LaneAreaDetector(this, laneAreaDetectorId);
}
// Polygon methods
std::list<std::string> getPolygonIds();
void addPolygon(std::string polyId, std::string polyType, const TraCIColor& color, bool filled, int32_t layer, const std::list<Coord>& points);
class VEINS_API Polygon {
public:
Polygon(TraCICommandInterface* traci, std::string polyId)
: traci(traci)
, polyId(polyId)
{
connection = &traci->connection;
}
std::string getTypeId();
std::list<Coord> getShape();
void setShape(const std::list<Coord>& points);
void remove(int32_t layer);
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string polyId;
};
Polygon polygon(std::string polyId)
{
return Polygon(this, polyId);
}
// Poi methods
std::list<std::string> getPoiIds();
void addPoi(std::string poiId, std::string poiType, const TraCIColor& color, int32_t layer, const Coord& pos);
class VEINS_API Poi {
public:
Poi(TraCICommandInterface* traci, std::string poiId)
: traci(traci)
, poiId(poiId)
{
connection = &traci->connection;
}
void remove(int32_t layer);
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string poiId;
};
Poi poi(std::string poiId)
{
return Poi(this, poiId);
}
// Junction methods
std::list<std::string> getJunctionIds();
class VEINS_API Junction {
public:
Junction(TraCICommandInterface* traci, std::string junctionId)
: traci(traci)
, junctionId(junctionId)
{
connection = &traci->connection;
}
Coord getPosition();
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string junctionId;
};
Junction junction(std::string junctionId)
{
return Junction(this, junctionId);
}
// Route methods
std::list<std::string> getRouteIds();
class VEINS_API Route {
public:
Route(TraCICommandInterface* traci, std::string routeId)
: traci(traci)
, routeId(routeId)
{
connection = &traci->connection;
}
std::list<std::string> getRoadIds();
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string routeId;
};
Route route(std::string routeId)
{
return Route(this, routeId);
}
// Vehicletype methods
std::list<std::string> getVehicleTypeIds();
// GuiView methods
std::list<std::string> getGuiViewIds();
class VEINS_API GuiView : public HasLogProxy {
public:
GuiView(TraCICommandInterface* traci, std::string viewId)
: HasLogProxy(traci->owner)
, traci(traci)
, viewId(viewId)
{
connection = &traci->connection;
}
std::string getScheme();
void setScheme(std::string name);
double getZoom();
void setZoom(double zoom);
void setBoundary(Coord p1, Coord p2);
void takeScreenshot(std::string filename = "", int32_t width = -1, int32_t height = -1);
/**
* Track the vehicle identified by vehicleId in the Sumo GUI.
*/
void trackVehicle(std::string vehicleId);
protected:
TraCICommandInterface* traci;
TraCIConnection* connection;
std::string viewId;
};
GuiView guiView(std::string viewId)
{
return GuiView(this, viewId);
}
private:
struct VersionConfig {
unsigned version;
uint8_t timeType;
uint8_t netBoundaryType;
uint8_t timeStepCmd;
};
TraCIConnection& connection;
bool ignoreGuiCommands;
static const std::map<uint32_t, VersionConfig> versionConfigs;
VersionConfig versionConfig;
std::string genericGetString(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
Coord genericGetCoord(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
double genericGetDouble(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
simtime_t genericGetTime(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
int32_t genericGetInt(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
std::list<std::string> genericGetStringList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
std::list<Coord> genericGetCoordList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId, TraCIConnection::Result* result = nullptr);
};
} // namespace veins
| 18,086 | 33.385932 | 255 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIConnection.cc | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#define WANT_WINSOCK2
#include <platdep/sockets.h>
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#include <ws2tcpip.h>
#else
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
#include <algorithm>
#include <functional>
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
using namespace veins::TraCIConstants;
namespace veins {
struct traci2omnet_functor : public std::unary_function<TraCICoord, Coord> {
traci2omnet_functor(const TraCIConnection& owner)
: owner(owner)
{
}
Coord operator()(const TraCICoord& coord) const
{
return owner.traci2omnet(coord);
}
const TraCIConnection& owner;
};
SOCKET socket(void* ptr)
{
ASSERT(ptr);
return *static_cast<SOCKET*>(ptr);
}
TraCIConnection::Result::Result()
: success(false)
, not_impl(false)
, message()
{
}
TraCIConnection::Result::Result(bool success, bool not_impl, std::string message)
: success(success)
, not_impl(false)
, message(message)
{
}
TraCIConnection::TraCIConnection(cComponent* owner, void* ptr)
: HasLogProxy(owner)
, socketPtr(ptr)
{
ASSERT(socketPtr);
}
TraCIConnection::~TraCIConnection()
{
if (socketPtr) {
closesocket(socket(socketPtr));
delete static_cast<SOCKET*>(socketPtr);
}
}
TraCIConnection* TraCIConnection::connect(cComponent* owner, const char* host, int port)
{
EV_STATICCONTEXT;
EV_INFO << "TraCIScenarioManager connecting to TraCI server" << endl;
if (initsocketlibonce() != 0) throw cRuntimeError("Could not init socketlib");
in_addr addr;
struct hostent* host_ent;
struct in_addr saddr;
saddr.s_addr = inet_addr(host);
if (saddr.s_addr != static_cast<unsigned int>(-1)) {
addr = saddr;
}
else if ((host_ent = gethostbyname(host))) {
addr = *((struct in_addr*) host_ent->h_addr_list[0]);
}
else {
throw cRuntimeError("Invalid TraCI server address: %s", host);
return nullptr;
}
sockaddr_in address;
sockaddr* address_p = (sockaddr*) &address;
memset(address_p, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = addr.s_addr;
SOCKET* socketPtr = new SOCKET();
if (*socketPtr < 0) throw cRuntimeError("Could not create socket to connect to TraCI server");
for (int tries = 1; tries <= 10; ++tries) {
*socketPtr = ::socket(AF_INET, SOCK_STREAM, 0);
if (::connect(*socketPtr, address_p, sizeof(address)) >= 0) break;
closesocket(socket(socketPtr));
std::stringstream ss;
ss << "Could not connect to TraCI server; error message: " << sock_errno() << ": " << strerror(sock_errno());
std::string msg = ss.str();
int sleepDuration = tries * .25 + 1;
if (tries >= 10) {
throw cRuntimeError(msg.c_str());
}
else if (tries == 3) {
EV_WARN << msg << " -- Will retry in " << sleepDuration << " second(s)." << std::endl;
}
sleep(sleepDuration);
}
{
int x = 1;
::setsockopt(*socketPtr, IPPROTO_TCP, TCP_NODELAY, (const char*) &x, sizeof(x));
}
return new TraCIConnection(owner, socketPtr);
}
TraCIBuffer TraCIConnection::query(uint8_t commandId, const TraCIBuffer& buf, Result* result)
{
sendMessage(makeTraCICommand(commandId, buf));
TraCIBuffer obuf(receiveMessage());
uint8_t cmdLength;
obuf >> cmdLength;
uint8_t commandResp;
obuf >> commandResp;
ASSERT(commandResp == commandId);
uint8_t resultCode;
obuf >> resultCode;
std::string description;
obuf >> description;
if (result != nullptr) {
result->success = (resultCode == RTYPE_OK);
result->not_impl = (resultCode == RTYPE_NOTIMPLEMENTED);
result->message = description;
}
else {
if (resultCode == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported command 0x%2x not implemented (\"%s\"). Might need newer version.", commandId, description.c_str());
if (resultCode != RTYPE_OK) throw cRuntimeError("TraCI server reported status %d executing command 0x%2x (\"%s\").", (int) resultCode, commandId, description.c_str());
}
return obuf;
}
std::string TraCIConnection::receiveMessage()
{
if (!socketPtr) throw cRuntimeError("Not connected to TraCI server");
uint32_t msgLength;
{
char buf2[sizeof(uint32_t)];
uint32_t bytesRead = 0;
while (bytesRead < sizeof(uint32_t)) {
int receivedBytes = ::recv(socket(socketPtr), reinterpret_cast<char*>(&buf2) + bytesRead, sizeof(uint32_t) - bytesRead, 0);
if (receivedBytes > 0) {
bytesRead += receivedBytes;
}
else if (receivedBytes == 0) {
throw cRuntimeError("Connection to TraCI server closed unexpectedly. Check your server's log");
}
else {
if (sock_errno() == EINTR) continue;
if (sock_errno() == EAGAIN) continue;
throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno()));
}
}
TraCIBuffer(std::string(buf2, sizeof(uint32_t))) >> msgLength;
}
uint32_t bufLength = msgLength - sizeof(msgLength);
char buf[bufLength];
{
EV_TRACE << "Reading TraCI message of " << bufLength << " bytes" << endl;
uint32_t bytesRead = 0;
while (bytesRead < bufLength) {
int receivedBytes = ::recv(socket(socketPtr), reinterpret_cast<char*>(&buf) + bytesRead, bufLength - bytesRead, 0);
if (receivedBytes > 0) {
bytesRead += receivedBytes;
}
else if (receivedBytes == 0) {
throw cRuntimeError("Connection to TraCI server closed unexpectedly. Check your server's log");
}
else {
if (sock_errno() == EINTR) continue;
if (sock_errno() == EAGAIN) continue;
throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno()));
}
}
}
return std::string(buf, bufLength);
}
void TraCIConnection::sendMessage(std::string buf)
{
if (!socketPtr) throw cRuntimeError("Not connected to TraCI server");
{
uint32_t msgLength = sizeof(uint32_t) + buf.length();
TraCIBuffer buf2 = TraCIBuffer();
buf2 << msgLength;
uint32_t bytesWritten = 0;
while (bytesWritten < sizeof(uint32_t)) {
ssize_t sentBytes = ::send(socket(socketPtr), buf2.str().c_str() + bytesWritten, sizeof(uint32_t) - bytesWritten, 0);
if (sentBytes > 0) {
bytesWritten += sentBytes;
}
else {
if (sock_errno() == EINTR) continue;
if (sock_errno() == EAGAIN) continue;
throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno()));
}
}
}
{
EV_TRACE << "Writing TraCI message of " << buf.length() << " bytes" << endl;
uint32_t bytesWritten = 0;
while (bytesWritten < buf.length()) {
ssize_t sentBytes = ::send(socket(socketPtr), buf.c_str() + bytesWritten, buf.length() - bytesWritten, 0);
if (sentBytes > 0) {
bytesWritten += sentBytes;
}
else {
if (sock_errno() == EINTR) continue;
if (sock_errno() == EAGAIN) continue;
throw cRuntimeError("Connection to TraCI server lost. Check your server's log. Error message: %d: %s", sock_errno(), strerror(sock_errno()));
}
}
}
}
std::string makeTraCICommand(uint8_t commandId, const TraCIBuffer& buf)
{
if (sizeof(uint8_t) + sizeof(uint8_t) + buf.str().length() > 0xFF) {
uint32_t len = sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint8_t) + buf.str().length();
return (TraCIBuffer() << static_cast<uint8_t>(0) << len << commandId).str() + buf.str();
}
uint8_t len = sizeof(uint8_t) + sizeof(uint8_t) + buf.str().length();
return (TraCIBuffer() << len << commandId).str() + buf.str();
}
void TraCIConnection::setNetbounds(TraCICoord netbounds1, TraCICoord netbounds2, int margin)
{
coordinateTransformation.reset(new TraCICoordinateTransformation(netbounds1, netbounds2, margin));
}
Coord TraCIConnection::traci2omnet(TraCICoord coord) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->traci2omnet(coord);
}
std::list<Coord> TraCIConnection::traci2omnet(const std::list<TraCICoord>& list) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->traci2omnet(list);
}
TraCICoord TraCIConnection::omnet2traci(Coord coord) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->omnet2traci(coord);
}
std::list<TraCICoord> TraCIConnection::omnet2traci(const std::list<Coord>& list) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->omnet2traci(list);
}
Heading TraCIConnection::traci2omnetHeading(double heading) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->traci2omnetHeading(heading);
}
double TraCIConnection::omnet2traciHeading(Heading heading) const
{
ASSERT(coordinateTransformation.get());
return coordinateTransformation->omnet2traciHeading(heading);
}
} // namespace veins
| 10,707 | 32.567398 | 191 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIConnection.h | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <stdint.h>
#include <memory>
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCICoord.h"
#include "veins/modules/mobility/traci/TraCICoordinateTransformation.h"
#include "veins/base/utils/Coord.h"
#include "veins/base/utils/Heading.h"
#include "veins/modules/utility/HasLogProxy.h"
namespace veins {
class VEINS_API TraCIConnection : public HasLogProxy {
public:
class VEINS_API Result {
public:
Result();
Result(bool success, bool not_impl, std::string message);
bool success;
bool not_impl;
std::string message;
};
static TraCIConnection* connect(cComponent* owner, const char* host, int port);
void setNetbounds(TraCICoord netbounds1, TraCICoord netbounds2, int margin);
~TraCIConnection();
/**
* sends a single command via TraCI, checks status response, returns additional responses.
* @param commandId: command to send
* @param buf: additional parameters to send
* @param result: where to store return value (if set to nullptr, any return value other than RTYPE_OK will trigger an exception).
*/
TraCIBuffer query(uint8_t commandId, const TraCIBuffer& buf = TraCIBuffer(), Result* result = nullptr);
/**
* sends a message via TraCI (after adding the header)
*/
void sendMessage(std::string buf);
/**
* receives a message via TraCI (and strips the header)
*/
std::string receiveMessage();
/**
* convert TraCI heading to OMNeT++ heading (in rad)
*/
Heading traci2omnetHeading(double heading) const;
/**
* convert OMNeT++ heading (in rad) to TraCI heading
*/
double omnet2traciHeading(Heading heading) const;
/**
* convert TraCI coordinates to OMNeT++ coordinates
*/
Coord traci2omnet(TraCICoord coord) const;
std::list<Coord> traci2omnet(const std::list<TraCICoord>&) const;
/**
* convert OMNeT++ coordinates to TraCI coordinates
*/
TraCICoord omnet2traci(Coord coord) const;
std::list<TraCICoord> omnet2traci(const std::list<Coord>&) const;
private:
TraCIConnection(cComponent* owner, void* ptr);
void* socketPtr;
std::unique_ptr<TraCICoordinateTransformation> coordinateTransformation;
};
/**
* returns byte-buffer containing a TraCI command with optional parameters
*/
std::string makeTraCICommand(uint8_t commandId, const TraCIBuffer& buf = TraCIBuffer());
} // namespace veins
| 3,398 | 31.066038 | 134 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIConstants.h | //
// Copyright (C) 2019 Universidad Nacional de Colombia, Politecnico Jaime Isaza Cadavid.
// Copyright (C) 2019 Andres Acosta, Jorge Espinosa, Jairo Espinosa
// Copyright (C) 2009 Rodney Thomson
// Copyright (C) 2008 Rodney Thomson
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: BSD-3-Clause
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution
// * Neither the name of Universidad Nacional de Colombia, Politécnico Jaime Isaza Cadavid nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// TraCI4Matlab 3.0.0.0
// $Id: constants.m 53 2019-01-03 15:18:31Z afacostag $
// The SUMO hexadecimal constants.
// Authors: Andres Acosta, Jairo Espinosa, Jorge Espinosa.
#pragma once
namespace veins {
namespace TraCIConstants {
const uint32_t TRACI_VERSION = 19;
const double INVALID_DOUBLE_VALUE = -1073741824;
const int32_t INVALID_INT_VALUE = -1073741824;
const uint8_t ADD = 0x80;
const uint8_t ADD_FULL = 0x85;
const uint8_t APPEND_STAGE = 0xc4;
const int8_t ARRIVALFLAG_LANE_CURRENT = -0x02;
const int8_t ARRIVALFLAG_POS_MAX = -0x03;
const int8_t ARRIVALFLAG_POS_RANDOM = -0x02;
const int8_t ARRIVALFLAG_SPEED_CURRENT = -0x02;
const uint8_t AUTOMATIC_CONTEXT_SUBSCRIPTION = 0x03;
const uint8_t AUTOMATIC_VARIABLES_SUBSCRIPTION = 0x02;
const uint8_t CMD_ADD_SUBSCRIPTION_FILTER = 0x7e;
const uint8_t CMD_CHANGELANE = 0x13;
const uint8_t CMD_CHANGESUBLANE = 0x15;
const uint8_t CMD_CHANGETARGET = 0x31;
const uint8_t CMD_CLEAR_PENDING_VEHICLES = 0x94;
const uint8_t CMD_CLOSE = 0x7F;
const uint8_t CMD_GETVERSION = 0x00;
const uint8_t CMD_GET_EDGE_VARIABLE = 0xaa;
const uint8_t CMD_GET_GUI_VARIABLE = 0xac;
const uint8_t CMD_GET_INDUCTIONLOOP_VARIABLE = 0xa0;
const uint8_t CMD_GET_JUNCTION_VARIABLE = 0xa9;
const uint8_t CMD_GET_LANEAREA_VARIABLE = 0xad;
const uint8_t CMD_GET_LANE_VARIABLE = 0xa3;
const uint8_t CMD_GET_MULTIENTRYEXIT_VARIABLE = 0xa1; // renamed for compatibility
const uint8_t CMD_GET_PERSON_VARIABLE = 0xae;
const uint8_t CMD_GET_POI_VARIABLE = 0xa7;
const uint8_t CMD_GET_POLYGON_VARIABLE = 0xa8;
const uint8_t CMD_GET_ROUTE_VARIABLE = 0xa6;
const uint8_t CMD_GET_SIM_VARIABLE = 0xab;
const uint8_t CMD_GET_TL_VARIABLE = 0xa2;
const uint8_t CMD_GET_VEHICLETYPE_VARIABLE = 0xa5;
const uint8_t CMD_GET_VEHICLE_VARIABLE = 0xa4;
const uint8_t CMD_LOAD = 0x01;
const uint8_t CMD_OPENGAP = 0x16;
const uint8_t CMD_REROUTE_EFFORT = 0x91;
const uint8_t CMD_REROUTE_TO_PARKING = 0xc2;
const uint8_t CMD_REROUTE_TRAVELTIME = 0x90;
const uint8_t CMD_RESUME = 0x19;
const uint8_t CMD_SAVE_SIMSTATE = 0x95;
const uint8_t CMD_SETORDER = 0x03;
const uint8_t CMD_SET_EDGE_VARIABLE = 0xca;
const uint8_t CMD_SET_GUI_VARIABLE = 0xcc;
const uint8_t CMD_SET_JUNCTION_VARIABLE = 0xc9;
const uint8_t CMD_SET_LANE_VARIABLE = 0xc3;
const uint8_t CMD_SET_PERSON_VARIABLE = 0xce;
const uint8_t CMD_SET_POI_VARIABLE = 0xc7;
const uint8_t CMD_SET_POLYGON_VARIABLE = 0xc8;
const uint8_t CMD_SET_ROUTE_VARIABLE = 0xc6;
const uint8_t CMD_SET_SIM_VARIABLE = 0xcb;
const uint8_t CMD_SET_TL_VARIABLE = 0xc2;
const uint8_t CMD_SET_VEHICLETYPE_VARIABLE = 0xc5;
const uint8_t CMD_SET_VEHICLE_VARIABLE = 0xc4;
const uint8_t CMD_SIMSTEP = 0x02;
const uint8_t CMD_SIMSTEP2 = 0x02; // Veins specific (called CMD_SIMSTEP in TraCI)
const uint8_t CMD_SLOWDOWN = 0x14;
const uint8_t CMD_STOP = 0x12;
const uint8_t CMD_SUBSCRIBE_EDGE_CONTEXT = 0x8a;
const uint8_t CMD_SUBSCRIBE_EDGE_VARIABLE = 0xda;
const uint8_t CMD_SUBSCRIBE_GUI_CONTEXT = 0x8c;
const uint8_t CMD_SUBSCRIBE_GUI_VARIABLE = 0xdc;
const uint8_t CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x80;
const uint8_t CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xd0;
const uint8_t CMD_SUBSCRIBE_JUNCTION_CONTEXT = 0x89;
const uint8_t CMD_SUBSCRIBE_JUNCTION_VARIABLE = 0xd9;
const uint8_t CMD_SUBSCRIBE_LANEAREA_CONTEXT = 0x8d;
const uint8_t CMD_SUBSCRIBE_LANEAREA_VARIABLE = 0xdd;
const uint8_t CMD_SUBSCRIBE_LANE_CONTEXT = 0x83;
const uint8_t CMD_SUBSCRIBE_LANE_VARIABLE = 0xd3;
const uint8_t CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x81; // renamed for compatibility
const uint8_t CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xd1; // renamed for compatibility
const uint8_t CMD_SUBSCRIBE_PERSON_CONTEXT = 0x8e;
const uint8_t CMD_SUBSCRIBE_PERSON_VARIABLE = 0xde;
const uint8_t CMD_SUBSCRIBE_POI_CONTEXT = 0x87;
const uint8_t CMD_SUBSCRIBE_POI_VARIABLE = 0xd7;
const uint8_t CMD_SUBSCRIBE_POLYGON_CONTEXT = 0x88;
const uint8_t CMD_SUBSCRIBE_POLYGON_VARIABLE = 0xd8;
const uint8_t CMD_SUBSCRIBE_ROUTE_CONTEXT = 0x86;
const uint8_t CMD_SUBSCRIBE_ROUTE_VARIABLE = 0xd6;
const uint8_t CMD_SUBSCRIBE_SIM_CONTEXT = 0x8b;
const uint8_t CMD_SUBSCRIBE_SIM_VARIABLE = 0xdb;
const uint8_t CMD_SUBSCRIBE_TL_CONTEXT = 0x82;
const uint8_t CMD_SUBSCRIBE_TL_VARIABLE = 0xd2;
const uint8_t CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x85;
const uint8_t CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xd5;
const uint8_t CMD_SUBSCRIBE_VEHICLE_CONTEXT = 0x84;
const uint8_t CMD_SUBSCRIBE_VEHICLE_VARIABLE = 0xd4;
const uint8_t COPY = 0x88;
const int8_t DEPARTFLAG_CONTAINER_TRIGGERED = -0x02;
const int8_t DEPARTFLAG_LANE_ALLOWED_FREE = -0x04;
const int8_t DEPARTFLAG_LANE_BEST_FREE = -0x05;
const int8_t DEPARTFLAG_LANE_FIRST_ALLOWED = -0x06;
const int8_t DEPARTFLAG_LANE_FREE = -0x03;
const int8_t DEPARTFLAG_LANE_RANDOM = -0x02;
const int8_t DEPARTFLAG_NOW = -0x03;
const int8_t DEPARTFLAG_POS_BASE = -0x04;
const int8_t DEPARTFLAG_POS_FREE = -0x03;
const int8_t DEPARTFLAG_POS_LAST = -0x05;
const int8_t DEPARTFLAG_POS_RANDOM = -0x02;
const int8_t DEPARTFLAG_POS_RANDOM_FREE = -0x06;
const int8_t DEPARTFLAG_SPEED_MAX = -0x03;
const int8_t DEPARTFLAG_SPEED_RANDOM = -0x02;
const int8_t DEPARTFLAG_TRIGGERED = -0x01;
const uint8_t DISTANCE_REQUEST = 0x83;
const uint8_t FILTER_TYPE_DOWNSTREAM_DIST = 0x03;
const uint8_t FILTER_TYPE_LANES = 0x01;
const uint8_t FILTER_TYPE_LEAD_FOLLOW = 0x05;
const uint8_t FILTER_TYPE_NONE = 0x00;
const uint8_t FILTER_TYPE_NOOPPOSITE = 0x02;
const uint8_t FILTER_TYPE_TURN = 0x07;
const uint8_t FILTER_TYPE_UPSTREAM_DIST = 0x04;
const uint8_t FILTER_TYPE_VCLASS = 0x08;
const uint8_t FILTER_TYPE_VTYPE = 0x09;
const uint8_t FIND_INTERMODAL_ROUTE = 0x87;
const uint8_t FIND_ROUTE = 0x86;
const uint8_t GENERIC_ATTRIBUTE = 0x03;
const uint8_t ID_COUNT = 0x01;
const uint8_t ID_LIST = 0x00;
const uint8_t JAM_LENGTH_METERS = 0x19;
const uint8_t JAM_LENGTH_VEHICLE = 0x18;
const uint8_t LANE_ALLOWED = 0x34;
const uint8_t LANE_DISALLOWED = 0x35;
const uint8_t LANE_EDGE_ID = 0x31;
const uint8_t LANE_LINKS = 0x33;
const uint8_t LANE_LINK_NUMBER = 0x30;
const uint8_t LAST_STEP_LENGTH = 0x15;
const uint8_t LAST_STEP_MEAN_SPEED = 0x11;
const uint8_t LAST_STEP_OCCUPANCY = 0x13;
const uint8_t LAST_STEP_PERSON_ID_LIST = 0x1a;
const uint8_t LAST_STEP_TIME_SINCE_DETECTION = 0x16;
const uint8_t LAST_STEP_VEHICLE_DATA = 0x17;
const uint8_t LAST_STEP_VEHICLE_HALTING_NUMBER = 0x14;
const uint8_t LAST_STEP_VEHICLE_ID_LIST = 0x12;
const uint8_t LAST_STEP_VEHICLE_NUMBER = 0x10;
const int32_t MAX_ORDER = 1073741824;
const uint8_t MOVE_TO_XY = 0xb4;
const uint8_t OBJECT_VARIABLES_SUBSCRIPTION = 0x02; // Veins specific (called AUTOMATIC_VARIABLES_SUBSCRIPTION in TraCI)
const uint8_t POSITION_2D = 0x01;
const uint8_t POSITION_3D = 0x03;
const uint8_t POSITION_CONVERSION = 0x82;
const uint8_t POSITION_LON_LAT = 0x00;
const uint8_t POSITION_LON_LAT_ALT = 0x02;
const uint8_t POSITION_ROADMAP = 0x04;
const uint8_t REMOVE = 0x81;
const uint8_t REMOVE_ARRIVED = 0x02;
const uint8_t REMOVE_PARKING = 0x01;
const uint8_t REMOVE_STAGE = 0xc5;
const uint8_t REMOVE_TELEPORT = 0x00;
const uint8_t REMOVE_TELEPORT_ARRIVED = 0x04;
const uint8_t REMOVE_VAPORIZED = 0x03;
const uint8_t REQUEST_AIRDIST = 0x00;
const uint8_t REQUEST_DRIVINGDIST = 0x01;
const uint8_t RESPONSE_GET_EDGE_VARIABLE = 0xba;
const uint8_t RESPONSE_GET_GUI_VARIABLE = 0xbc;
const uint8_t RESPONSE_GET_INDUCTIONLOOP_VARIABLE = 0xb0;
const uint8_t RESPONSE_GET_JUNCTION_VARIABLE = 0xb9;
const uint8_t RESPONSE_GET_LANEAREA_VARIABLE = 0xbd;
const uint8_t RESPONSE_GET_LANE_VARIABLE = 0xb3;
const uint8_t RESPONSE_GET_MULTIENTRYEXIT_VARIABLE = 0xb1; // renamed for compatibility
const uint8_t RESPONSE_GET_PERSON_VARIABLE = 0xbe;
const uint8_t RESPONSE_GET_POI_VARIABLE = 0xb7;
const uint8_t RESPONSE_GET_POLYGON_VARIABLE = 0xb8;
const uint8_t RESPONSE_GET_ROUTE_VARIABLE = 0xb6;
const uint8_t RESPONSE_GET_SIM_VARIABLE = 0xbb;
const uint8_t RESPONSE_GET_TL_VARIABLE = 0xb2;
const uint8_t RESPONSE_GET_VEHICLETYPE_VARIABLE = 0xb5;
const uint8_t RESPONSE_GET_VEHICLE_VARIABLE = 0xb4;
const uint8_t RESPONSE_SUBSCRIBE_EDGE_CONTEXT = 0x9a;
const uint8_t RESPONSE_SUBSCRIBE_EDGE_VARIABLE = 0xea;
const uint8_t RESPONSE_SUBSCRIBE_GUI_CONTEXT = 0x9c;
const uint8_t RESPONSE_SUBSCRIBE_GUI_VARIABLE = 0xec;
const uint8_t RESPONSE_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x90;
const uint8_t RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xe0;
const uint8_t RESPONSE_SUBSCRIBE_JUNCTION_CONTEXT = 0x99;
const uint8_t RESPONSE_SUBSCRIBE_JUNCTION_VARIABLE = 0xe9;
const uint8_t RESPONSE_SUBSCRIBE_LANEAREA_CONTEXT = 0x9d;
const uint8_t RESPONSE_SUBSCRIBE_LANEAREA_VARIABLE = 0xed;
const uint8_t RESPONSE_SUBSCRIBE_LANE_CONTEXT = 0x93;
const uint8_t RESPONSE_SUBSCRIBE_LANE_VARIABLE = 0xe3;
const uint8_t RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x91; // renamed for compatibility
const uint8_t RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xe1; // renamed for compatibility
const uint8_t RESPONSE_SUBSCRIBE_PERSON_CONTEXT = 0x9e;
const uint8_t RESPONSE_SUBSCRIBE_PERSON_VARIABLE = 0xee;
const uint8_t RESPONSE_SUBSCRIBE_POI_CONTEXT = 0x97;
const uint8_t RESPONSE_SUBSCRIBE_POI_VARIABLE = 0xe7;
const uint8_t RESPONSE_SUBSCRIBE_POLYGON_CONTEXT = 0x98;
const uint8_t RESPONSE_SUBSCRIBE_POLYGON_VARIABLE = 0xe8;
const uint8_t RESPONSE_SUBSCRIBE_ROUTE_CONTEXT = 0x96;
const uint8_t RESPONSE_SUBSCRIBE_ROUTE_VARIABLE = 0xe6;
const uint8_t RESPONSE_SUBSCRIBE_SIM_CONTEXT = 0x9b;
const uint8_t RESPONSE_SUBSCRIBE_SIM_VARIABLE = 0xeb;
const uint8_t RESPONSE_SUBSCRIBE_TL_CONTEXT = 0x92;
const uint8_t RESPONSE_SUBSCRIBE_TL_VARIABLE = 0xe2;
const uint8_t RESPONSE_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x95;
const uint8_t RESPONSE_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xe5;
const uint8_t RESPONSE_SUBSCRIBE_VEHICLE_CONTEXT = 0x94;
const uint8_t RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE = 0xe4;
const uint8_t ROUTING_MODE_AGGREGATED = 0x01;
const uint8_t ROUTING_MODE_COMBINED = 0x03;
const uint8_t ROUTING_MODE_DEFAULT = 0x00;
const uint8_t ROUTING_MODE_EFFORT = 0x02;
const uint8_t RTYPE_ERR = 0xFF;
const uint8_t RTYPE_NOTIMPLEMENTED = 0x01;
const uint8_t RTYPE_OK = 0x00;
const uint8_t STAGE_DRIVING = 0x03;
const uint8_t STAGE_WAITING = 0x01;
const uint8_t STAGE_WAITING_FOR_DEPART = 0x00;
const uint8_t STAGE_WALKING = 0x02;
const uint8_t STOP_BUS_STOP = 0x08;
const uint8_t STOP_CHARGING_STATION = 0x20;
const uint8_t STOP_CONTAINER_STOP = 0x10;
const uint8_t STOP_CONTAINER_TRIGGERED = 0x04;
const uint8_t STOP_DEFAULT = 0x00;
const uint8_t STOP_PARKING = 0x01;
const uint8_t STOP_PARKING_AREA = 0x40;
const uint8_t STOP_TRIGGERED = 0x02;
const uint8_t SURROUNDING_VARIABLES_SUBSCRIPTION = 0x03; // Veins specific (called AUTOMATIC_CONTEXT_SUBSCRIPTION in TraCI)
const uint8_t TL_COMPLETE_DEFINITION_RYG = 0x2b;
const uint8_t TL_COMPLETE_PROGRAM_RYG = 0x2c;
const uint8_t TL_CONTROLLED_JUNCTIONS = 0x2a;
const uint8_t TL_CONTROLLED_LANES = 0x26;
const uint8_t TL_CONTROLLED_LINKS = 0x27;
const uint8_t TL_CURRENT_PHASE = 0x28;
const uint8_t TL_CURRENT_PROGRAM = 0x29;
const uint8_t TL_EXTERNAL_STATE = 0x2e;
const uint8_t TL_NEXT_SWITCH = 0x2d;
const uint8_t TL_PHASE_DURATION = 0x24;
const uint8_t TL_PHASE_INDEX = 0x22;
const uint8_t TL_PROGRAM = 0x23;
const uint8_t TL_RED_YELLOW_GREEN_STATE = 0x20;
const uint8_t TYPE_BOUNDINGBOX = 0x05; // Retained for backwards compatibility
const uint8_t TYPE_BYTE = 0x08;
const uint8_t TYPE_COLOR = 0x11;
const uint8_t TYPE_COMPOUND = 0x0F;
const uint8_t TYPE_DOUBLE = 0x0B;
const uint8_t TYPE_INTEGER = 0x09;
const uint8_t TYPE_POLYGON = 0x06;
const uint8_t TYPE_STRING = 0x0C;
const uint8_t TYPE_STRINGLIST = 0x0E;
const uint8_t TYPE_UBYTE = 0x07;
const uint8_t VAR_ACCEL = 0x46;
const uint8_t VAR_ACCELERATION = 0x72;
const uint8_t VAR_ACCUMULATED_WAITING_TIME = 0x87;
const uint8_t VAR_ACTIONSTEPLENGTH = 0x7d;
const uint8_t VAR_ALLOWED_SPEED = 0xb7;
const uint8_t VAR_ANGLE = 0x43;
const uint8_t VAR_APPARENT_DECEL = 0x7c;
const uint8_t VAR_ARRIVED_VEHICLES_IDS = 0x7a;
const uint8_t VAR_ARRIVED_VEHICLES_NUMBER = 0x79;
const uint8_t VAR_BEST_LANES = 0xb2;
const uint8_t VAR_BUS_STOP_WAITING = 0x67;
const uint8_t VAR_CO2EMISSION = 0x60;
const uint8_t VAR_COEMISSION = 0x61;
const uint8_t VAR_COLLIDING_VEHICLES_IDS = 0x81;
const uint8_t VAR_COLLIDING_VEHICLES_NUMBER = 0x80;
const uint8_t VAR_COLOR = 0x45;
const uint8_t VAR_CURRENT_TRAVELTIME = 0x5a;
const uint8_t VAR_DECEL = 0x47;
const uint8_t VAR_DELTA_T = 0x7b;
const uint8_t VAR_DEPARTED_VEHICLES_IDS = 0x74;
const uint8_t VAR_DEPARTED_VEHICLES_NUMBER = 0x73;
const uint8_t VAR_DISTANCE = 0x84;
const uint8_t VAR_EDGES = 0x54;
const uint8_t VAR_EDGE_EFFORT = 0x59;
const uint8_t VAR_EDGE_TRAVELTIME = 0x58;
const uint8_t VAR_ELECTRICITYCONSUMPTION = 0x71;
const uint8_t VAR_EMERGENCYSTOPPING_VEHICLES_IDS = 0x8a;
const uint8_t VAR_EMERGENCYSTOPPING_VEHICLES_NUMBER = 0x89;
const uint8_t VAR_EMERGENCY_DECEL = 0x7b;
const uint8_t VAR_EMISSIONCLASS = 0x4a;
const uint8_t VAR_FILL = 0x55;
const uint8_t VAR_FOES = 0x37;
const uint8_t VAR_FUELCONSUMPTION = 0x65;
const uint8_t VAR_HAS_VIEW = 0xa7;
const uint8_t VAR_HCEMISSION = 0x62;
const uint8_t VAR_HEIGHT = 0xbc;
const uint8_t VAR_IMPERFECTION = 0x5d;
const uint8_t VAR_LANECHANGE_MODE = 0xb6;
const uint8_t VAR_LANEPOSITION = 0x56;
const uint8_t VAR_LANEPOSITION_LAT = 0xb8;
const uint8_t VAR_LANE_ID = 0x51;
const uint8_t VAR_LANE_INDEX = 0x52;
const uint8_t VAR_LASTACTIONTIME = 0x7f;
const uint8_t VAR_LATALIGNMENT = 0xb9;
const uint8_t VAR_LEADER = 0x68;
const uint8_t VAR_LENGTH = 0x44;
const uint8_t VAR_LINE = 0xbd;
const uint8_t VAR_LOADED_VEHICLES_IDS = 0x72;
const uint8_t VAR_LOADED_VEHICLES_NUMBER = 0x71;
const uint8_t VAR_MAXSPEED = 0x41;
const uint8_t VAR_MAXSPEED_LAT = 0xba;
const uint8_t VAR_MINGAP = 0x4c;
const uint8_t VAR_MINGAP_LAT = 0xbb;
const uint8_t VAR_MIN_EXPECTED_VEHICLES = 0x7d;
const uint8_t VAR_MOVE_TO = 0x5c;
const uint8_t VAR_MOVE_TO_VTD = 0xb4; // Veins specific (called MOVE_TO_XY in TraCI)
const uint8_t VAR_NAME = 0x1b;
const uint8_t VAR_NET_BOUNDING_BOX = 0x7c;
const uint8_t VAR_NEXT_EDGE = 0xc1;
const uint8_t VAR_NEXT_STOPS = 0x73;
const uint8_t VAR_NEXT_TLS = 0x70;
const uint8_t VAR_NOISEEMISSION = 0x66;
const uint8_t VAR_NOXEMISSION = 0x64;
const uint8_t VAR_PARAMETER = 0x7e;
const uint8_t VAR_PARKING_ENDING_VEHICLES_IDS = 0x6f;
const uint8_t VAR_PARKING_ENDING_VEHICLES_NUMBER = 0x6e;
const uint8_t VAR_PARKING_STARTING_VEHICLES_IDS = 0x6d;
const uint8_t VAR_PARKING_STARTING_VEHICLES_NUMBER = 0x6c;
const uint8_t VAR_PERSON_NUMBER = 0x67;
const uint8_t VAR_PMXEMISSION = 0x63;
const uint8_t VAR_POSITION = 0x42;
const uint8_t VAR_POSITION3D = 0x39;
const uint8_t VAR_ROAD_ID = 0x50;
const uint8_t VAR_ROUTE = 0x57;
const uint8_t VAR_ROUTE_ID = 0x53;
const uint8_t VAR_ROUTE_INDEX = 0x69;
const uint8_t VAR_ROUTE_VALID = 0x92;
const uint8_t VAR_ROUTING_MODE = 0x89;
const uint8_t VAR_SCREENSHOT = 0xa5;
const uint8_t VAR_SHAPE = 0x4e;
const uint8_t VAR_SHAPECLASS = 0x4b;
const uint8_t VAR_SIGNALS = 0x5b;
const uint8_t VAR_SLOPE = 0x36;
const uint8_t VAR_SPEED = 0x40;
const uint8_t VAR_SPEEDSETMODE = 0xb3;
const uint8_t VAR_SPEED_DEVIATION = 0x5f;
const uint8_t VAR_SPEED_FACTOR = 0x5e;
const uint8_t VAR_SPEED_WITHOUT_TRACI = 0xb1;
const uint8_t VAR_STAGE = 0xc0;
const uint8_t VAR_STAGES_REMAINING = 0xc2;
const uint8_t VAR_STOPSTATE = 0xb5;
const uint8_t VAR_STOP_ENDING_VEHICLES_IDS = 0x6b;
const uint8_t VAR_STOP_ENDING_VEHICLES_NUMBER = 0x6a;
const uint8_t VAR_STOP_STARTING_VEHICLES_IDS = 0x69;
const uint8_t VAR_STOP_STARTING_VEHICLES_NUMBER = 0x68;
const uint8_t VAR_TAU = 0x48;
const uint8_t VAR_TELEPORT_ENDING_VEHICLES_IDS = 0x78;
const uint8_t VAR_TELEPORT_ENDING_VEHICLES_NUMBER = 0x77;
const uint8_t VAR_TELEPORT_STARTING_VEHICLES_IDS = 0x76;
const uint8_t VAR_TELEPORT_STARTING_VEHICLES_NUMBER = 0x75;
const uint8_t VAR_TIME = 0x66;
const uint8_t VAR_TIME_STEP = 0x70;
const uint8_t VAR_TRACK_VEHICLE = 0xa6;
const uint8_t VAR_TYPE = 0x4f;
const uint8_t VAR_UPDATE_BESTLANES = 0x6a;
const uint8_t VAR_VEHICLE = 0xc3;
const uint8_t VAR_VEHICLECLASS = 0x49;
const uint8_t VAR_VIA = 0xbe;
const uint8_t VAR_VIEW_BOUNDARY = 0xa3;
const uint8_t VAR_VIEW_OFFSET = 0xa1;
const uint8_t VAR_VIEW_SCHEMA = 0xa2;
const uint8_t VAR_VIEW_ZOOM = 0xa0;
const uint8_t VAR_WAITING_TIME = 0x7a;
const uint8_t VAR_WAITING_TIME_ACCUMULATED = 0x87; // Veins specific (called VAR_ACCUMULATED_WAITING_TIME in TraCI)
const uint8_t VAR_WIDTH = 0x4d;
} // namespace TraCIConstants
} // namespace veins
| 18,274 | 43.791667 | 123 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCICoord.h | //
// Copyright (C) 2006 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
namespace veins {
/**
* Coord equivalent for storing TraCI coordinates
*/
struct VEINS_API TraCICoord {
TraCICoord()
: x(0.0)
, y(0.0)
{
}
TraCICoord(double x, double y)
: x(x)
, y(y)
{
}
double x;
double y;
};
} // namespace veins
| 1,240 | 24.854167 | 76 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCICoordinateTransformation.cc | //
// Copyright (C) 2018 Dominik S. Buse <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCICoordinateTransformation.h"
namespace veins {
using OmnetCoord = TraCICoordinateTransformation::OmnetCoord;
using OmnetCoordList = TraCICoordinateTransformation::OmnetCoordList;
using TraCICoordList = TraCICoordinateTransformation::TraCICoordList;
using OmnetHeading = TraCICoordinateTransformation::OmnetHeading;
using TraCIHeading = TraCICoordinateTransformation::TraCIHeading;
TraCICoordinateTransformation::TraCICoordinateTransformation(TraCICoord topleft, TraCICoord bottomright, float margin)
: dimensions({bottomright.x - topleft.x, bottomright.y - topleft.y})
, topleft(topleft)
, bottomright(bottomright)
, margin(margin)
{
}
TraCICoord TraCICoordinateTransformation::omnet2traci(const OmnetCoord& coord) const
{
return {coord.x + topleft.x - margin, dimensions.y - (coord.y - topleft.y) + margin};
}
TraCICoordList TraCICoordinateTransformation::omnet2traci(const OmnetCoordList& coords) const
{
TraCICoordList result;
for (auto&& coord : coords) {
result.push_back(omnet2traci(coord));
}
return result;
}
TraCIHeading TraCICoordinateTransformation::omnet2traciHeading(OmnetHeading o) const
{
// convert to degrees
auto angle = o.getRad() * 180 / M_PI;
// rotate angle
angle = 90 - angle;
// normalize angle to -180 <= angle < 180
while (angle < -180) {
angle += 360;
}
while (angle >= 180) {
angle -= 360;
}
return angle;
}
OmnetCoord TraCICoordinateTransformation::traci2omnet(const TraCICoord& coord) const
{
return {coord.x - topleft.x + margin, dimensions.y - (coord.y - topleft.y) + margin};
}
OmnetCoordList TraCICoordinateTransformation::traci2omnet(const TraCICoordList& coords) const
{
OmnetCoordList result;
for (auto&& coord : coords) {
result.push_back(traci2omnet(coord));
}
return result;
}
OmnetHeading TraCICoordinateTransformation::traci2omnetHeading(TraCIHeading o) const
{
// rotate angle
auto angle = 90 - o;
// convert to rad
angle = angle * M_PI / 180.0;
// normalize angle to -M_PI <= angle < M_PI
while (angle < -M_PI) {
angle += 2 * M_PI;
}
while (angle >= M_PI) {
angle -= 2 * M_PI;
}
return OmnetHeading(angle);
}
} // end namespace veins
| 3,218 | 28.805556 | 118 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCICoordinateTransformation.h | //
// Copyright (C) 2018 Dominik S. Buse <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/modules/mobility/traci/TraCICoord.h"
#include "veins/base/utils/Coord.h"
#include "veins/base/utils/Heading.h"
#include <list>
namespace veins {
/**
* Helper class for converting SUMO coordinates to OMNeT++ Coordinates for a given network.
*/
class VEINS_API TraCICoordinateTransformation {
public:
using OmnetCoord = Coord;
using OmnetCoordList = std::list<OmnetCoord>;
using TraCICoordList = std::list<TraCICoord>;
using TraCIHeading = double;
using OmnetHeading = Heading;
TraCICoordinateTransformation(TraCICoord topleft, TraCICoord bottomright, float margin);
TraCICoord omnet2traci(const OmnetCoord& coord) const;
TraCICoordList omnet2traci(const OmnetCoordList& coords) const;
TraCIHeading omnet2traciHeading(OmnetHeading heading) const; /**< TraCI's heading interpretation: 0 is north, 90 is east */
OmnetCoord traci2omnet(const TraCICoord& coord) const;
OmnetCoordList traci2omnet(const TraCICoordList& coords) const;
OmnetHeading traci2omnetHeading(TraCIHeading heading) const; /**< OMNeT++'s heading interpretation: 0 is east, pi/2 is north */
private:
TraCICoord dimensions;
TraCICoord topleft;
TraCICoord bottomright;
float margin;
}; // end class NetworkCoordinateTranslator
} // end namespace veins
| 2,214 | 35.916667 | 132 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCILauncher.cc | //
// Copyright (C) 2006-2016 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/veins.h"
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#else
#include <sys/wait.h>
#endif
#include "veins/modules/mobility/traci/TraCILauncher.h"
using veins::TraCILauncher;
TraCILauncher::TraCILauncher(std::string commandLine)
{
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFOA);
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
char cmdline[32768];
strncpy(cmdline, commandLine.c_str(), sizeof(cmdline));
bool bSuccess = CreateProcess(0, cmdline, 0, 0, 1, NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, 0, 0, &si, &pi);
if (!bSuccess) {
std::string msg = "undefined error";
DWORD errorMessageID = ::GetLastError();
if (errorMessageID != 0) {
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
msg = message;
}
msg = std::string() + "Error launching TraCI server (\"" + commandLine + "\"): " + msg + ". Make sure you have set $PATH correctly.";
throw cRuntimeError(msg.c_str());
}
else {
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
#else
pid = fork();
if (pid == 0) {
signal(SIGINT, SIG_IGN);
int r = system(commandLine.c_str());
if (r == -1) {
throw cRuntimeError("Running \"%s\" failed during system()", commandLine.c_str());
}
if (WEXITSTATUS(r) != 0) {
throw cRuntimeError("Error launching TraCI server (\"%s\"): exited with code %d. Make sure you have set $PATH correctly.", commandLine.c_str(), WEXITSTATUS(r));
}
exit(1);
}
#endif
}
TraCILauncher::~TraCILauncher()
{
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#else
if (pid) {
// send SIGINT
kill(pid, 15);
}
#endif
}
| 3,252 | 32.885417 | 232 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCILauncher.h | //
// Copyright (C) 2006-2016 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
namespace veins {
/**
* @brief
* Launches a program (the TraCI server) when instantiated.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer
*
* @see TraCIMobility
* @see TraCIScenarioManager
*
*/
class VEINS_API TraCILauncher {
public:
TraCILauncher(std::string commandLine);
~TraCILauncher();
protected:
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#else
pid_t pid;
#endif
};
} // namespace veins
| 1,502 | 27.903846 | 113 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIMobility.cc | //
// Copyright (C) 2006-2012 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <limits>
#include <iostream>
#include <sstream>
#include "veins/modules/mobility/traci/TraCIMobility.h"
using namespace veins;
using veins::TraCIMobility;
Define_Module(veins::TraCIMobility);
const simsignal_t TraCIMobility::parkingStateChangedSignal = registerSignal("org_car2x_veins_modules_mobility_parkingStateChanged");
namespace {
const double MY_INFINITY = (std::numeric_limits<double>::has_infinity ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::max());
}
void TraCIMobility::Statistics::initialize()
{
firstRoadNumber = MY_INFINITY;
startTime = simTime();
totalTime = 0;
stopTime = 0;
minSpeed = MY_INFINITY;
maxSpeed = -MY_INFINITY;
totalDistance = 0;
totalCO2Emission = 0;
}
void TraCIMobility::Statistics::watch(cSimpleModule&)
{
}
void TraCIMobility::Statistics::recordScalars(cSimpleModule& module)
{
if (firstRoadNumber != MY_INFINITY) module.recordScalar("firstRoadNumber", firstRoadNumber);
module.recordScalar("startTime", startTime);
module.recordScalar("totalTime", totalTime);
module.recordScalar("stopTime", stopTime);
if (minSpeed != MY_INFINITY) module.recordScalar("minSpeed", minSpeed);
if (maxSpeed != -MY_INFINITY) module.recordScalar("maxSpeed", maxSpeed);
module.recordScalar("totalDistance", totalDistance);
module.recordScalar("totalCO2Emission", totalCO2Emission);
}
void TraCIMobility::initialize(int stage)
{
if (stage == 0) {
BaseMobility::initialize(stage);
hostPositionOffset = par("hostPositionOffset");
setHostSpeed = par("setHostSpeed");
accidentCount = par("accidentCount");
currentPosXVec.setName("posx");
currentPosYVec.setName("posy");
currentSpeedVec.setName("speed");
currentAccelerationVec.setName("acceleration");
currentCO2EmissionVec.setName("co2emission");
statistics.initialize();
statistics.watch(*this);
ASSERT(isPreInitialized);
isPreInitialized = false;
Coord nextPos = calculateHostPosition(roadPosition);
nextPos.z = move.getStartPosition().z;
move.setStart(nextPos);
move.setDirectionByVector(heading.toCoord());
move.setOrientationByVector(heading.toCoord());
if (this->setHostSpeed) {
move.setSpeed(speed);
}
isParking = false;
startAccidentMsg = nullptr;
stopAccidentMsg = nullptr;
manager = nullptr;
last_speed = -1;
if (accidentCount > 0) {
simtime_t accidentStart = par("accidentStart");
startAccidentMsg = new cMessage("scheduledAccident");
stopAccidentMsg = new cMessage("scheduledAccidentResolved");
scheduleAt(simTime() + accidentStart, startAccidentMsg);
}
}
else if (stage == 1) {
// don't call BaseMobility::initialize(stage) -- our parent will take care to call changePosition later
}
else {
BaseMobility::initialize(stage);
}
}
void TraCIMobility::finish()
{
statistics.stopTime = simTime();
statistics.recordScalars(*this);
cancelAndDelete(startAccidentMsg);
cancelAndDelete(stopAccidentMsg);
isPreInitialized = false;
}
void TraCIMobility::handleSelfMsg(cMessage* msg)
{
if (msg == startAccidentMsg) {
getVehicleCommandInterface()->setSpeed(0);
simtime_t accidentDuration = par("accidentDuration");
scheduleAt(simTime() + accidentDuration, stopAccidentMsg);
accidentCount--;
}
else if (msg == stopAccidentMsg) {
getVehicleCommandInterface()->setSpeed(-1);
if (accidentCount > 0) {
simtime_t accidentInterval = par("accidentInterval");
scheduleAt(simTime() + accidentInterval, startAccidentMsg);
}
}
}
void TraCIMobility::preInitialize(std::string external_id, const Coord& position, std::string road_id, double speed, Heading heading)
{
this->external_id = external_id;
this->lastUpdate = 0;
this->roadPosition = position;
this->road_id = road_id;
this->speed = speed;
this->heading = heading;
this->hostPositionOffset = par("hostPositionOffset");
this->setHostSpeed = par("setHostSpeed");
Coord nextPos = calculateHostPosition(roadPosition);
nextPos.z = move.getStartPosition().z;
move.setStart(nextPos);
move.setDirectionByVector(heading.toCoord());
move.setOrientationByVector(heading.toCoord());
if (this->setHostSpeed) {
move.setSpeed(speed);
}
isPreInitialized = true;
}
void TraCIMobility::nextPosition(const Coord& position, std::string road_id, double speed, Heading heading, VehicleSignalSet signals)
{
EV_DEBUG << "nextPosition " << position.x << " " << position.y << " " << road_id << " " << speed << " " << heading << std::endl;
isPreInitialized = false;
this->roadPosition = position;
this->road_id = road_id;
this->speed = speed;
this->heading = heading;
this->signals = signals;
changePosition();
ASSERT(getCurrentDirection() == heading.toCoord() and getCurrentDirection() == getCurrentOrientation());
}
void TraCIMobility::changePosition()
{
// ensure we're not called twice in one time step
ASSERT(lastUpdate != simTime());
// keep statistics (for current step)
currentPosXVec.record(move.getStartPos().x);
currentPosYVec.record(move.getStartPos().y);
Coord nextPos = calculateHostPosition(roadPosition);
nextPos.z = move.getStartPosition().z;
// keep statistics (relative to last step)
if (statistics.startTime != simTime()) {
simtime_t updateInterval = simTime() - this->lastUpdate;
double distance = move.getStartPos().distance(nextPos);
statistics.totalDistance += distance;
statistics.totalTime += updateInterval;
if (speed != -1) {
statistics.minSpeed = std::min(statistics.minSpeed, speed);
statistics.maxSpeed = std::max(statistics.maxSpeed, speed);
currentSpeedVec.record(speed);
if (last_speed != -1) {
double acceleration = (speed - last_speed) / updateInterval;
double co2emission = calculateCO2emission(speed, acceleration);
currentAccelerationVec.record(acceleration);
currentCO2EmissionVec.record(co2emission);
statistics.totalCO2Emission += co2emission * updateInterval.dbl();
}
last_speed = speed;
}
else {
last_speed = -1;
speed = -1;
}
}
this->lastUpdate = simTime();
// Update display string to show node is getting updates
auto hostMod = getParentModule();
if (std::string(hostMod->getDisplayString().getTagArg("veins", 0)) == ". ") {
hostMod->getDisplayString().setTagArg("veins", 0, " .");
}
else {
hostMod->getDisplayString().setTagArg("veins", 0, ". ");
}
move.setStart(Coord(nextPos.x, nextPos.y, move.getStartPosition().z)); // keep z position
move.setDirectionByVector(heading.toCoord());
move.setOrientationByVector(heading.toCoord());
if (this->setHostSpeed) {
move.setSpeed(speed);
}
fixIfHostGetsOutside();
updatePosition();
}
void TraCIMobility::changeParkingState(bool newState)
{
Enter_Method_Silent();
isParking = newState;
emit(parkingStateChangedSignal, this);
}
void TraCIMobility::fixIfHostGetsOutside()
{
Coord pos = move.getStartPos();
Coord dummy = Coord::ZERO;
double dum;
bool outsideX = (pos.x < 0) || (pos.x >= playgroundSizeX());
bool outsideY = (pos.y < 0) || (pos.y >= playgroundSizeY());
bool outsideZ = (!world->use2D()) && ((pos.z < 0) || (pos.z >= playgroundSizeZ()));
if (outsideX || outsideY || outsideZ) {
throw cRuntimeError("Tried moving host to (%f, %f) which is outside the playground", pos.x, pos.y);
}
handleIfOutside(RAISEERROR, pos, dummy, dummy, dum);
}
double TraCIMobility::calculateCO2emission(double v, double a) const
{
// Calculate CO2 emission parameters according to:
// Cappiello, A. and Chabini, I. and Nam, E.K. and Lue, A. and Abou Zeid, M., "A statistical model of vehicle emissions and fuel consumption," IEEE 5th International Conference on Intelligent Transportation Systems (IEEE ITSC), pp. 801-809, 2002
double A = 1000 * 0.1326; // W/m/s
double B = 1000 * 2.7384e-03; // W/(m/s)^2
double C = 1000 * 1.0843e-03; // W/(m/s)^3
double M = 1325.0; // kg
// power in W
double P_tract = A * v + B * v * v + C * v * v * v + M * a * v; // for sloped roads: +M*g*sin_theta*v
/*
// "Category 7 vehicle" (e.g. a '92 Suzuki Swift)
double alpha = 1.01;
double beta = 0.0162;
double delta = 1.90e-06;
double zeta = 0.252;
double alpha1 = 0.985;
*/
// "Category 9 vehicle" (e.g. a '94 Dodge Spirit)
double alpha = 1.11;
double beta = 0.0134;
double delta = 1.98e-06;
double zeta = 0.241;
double alpha1 = 0.973;
if (P_tract <= 0) return alpha1;
return alpha + beta * v * 3.6 + delta * v * v * v * (3.6 * 3.6 * 3.6) + zeta * a * v;
}
Coord TraCIMobility::calculateHostPosition(const Coord& vehiclePos) const
{
Coord corPos;
if (hostPositionOffset >= 0.001) {
// calculate antenna position of vehicle according to antenna offset
corPos = vehiclePos - (heading.toCoord() * hostPositionOffset);
}
else {
corPos = vehiclePos;
}
return corPos;
}
| 10,482 | 32.279365 | 249 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIMobility.h | //
// Copyright (C) 2006-2012 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <string>
#include <fstream>
#include <list>
#include <stdexcept>
#include "veins/base/modules/BaseMobility.h"
#include "veins/base/utils/FindModule.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/VehicleSignal.h"
#include "veins/base/utils/Heading.h"
namespace veins {
/**
* @brief
* Used in modules created by the TraCIScenarioManager.
*
* This module relies on the TraCIScenarioManager for state updates
* and can not be used on its own.
*
* TraCI server implementations do not differentiate between the orientation and direction of a vehicle.
* Thus, TraCIMobility::updatePosition sets the BaseMobility's orientation and direction to the same value.
* Said value is equivalent to the heading of the vehicle.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer, David Eckhoff, Luca Bedogni, Bastian Halmos, Stefan Joerer
*
* @see TraCIScenarioManager
* @see TraCIScenarioManagerLaunchd
*
* @ingroup mobility
*/
class VEINS_API TraCIMobility : public BaseMobility {
public:
class VEINS_API Statistics {
public:
double firstRoadNumber; /**< for statistics: number of first road we encountered (if road id can be expressed as a number) */
simtime_t startTime; /**< for statistics: start time */
simtime_t totalTime; /**< for statistics: total time travelled */
simtime_t stopTime; /**< for statistics: stop time */
double minSpeed; /**< for statistics: minimum value of currentSpeed */
double maxSpeed; /**< for statistics: maximum value of currentSpeed */
double totalDistance; /**< for statistics: total distance travelled */
double totalCO2Emission; /**< for statistics: total CO2 emission */
void initialize();
void watch(cSimpleModule& module);
void recordScalars(cSimpleModule& module);
};
const static simsignal_t parkingStateChangedSignal;
TraCIMobility()
: BaseMobility()
, isPreInitialized(false)
, manager(nullptr)
, commandInterface(nullptr)
, vehicleCommandInterface(nullptr)
{
}
~TraCIMobility() override
{
delete vehicleCommandInterface;
}
void initialize(int) override;
void finish() override;
void handleSelfMsg(cMessage* msg) override;
virtual void preInitialize(std::string external_id, const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan);
virtual void nextPosition(const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan, VehicleSignalSet signals = {VehicleSignal::undefined});
virtual void changePosition();
virtual void changeParkingState(bool);
virtual void setExternalId(std::string external_id)
{
this->external_id = external_id;
}
virtual std::string getExternalId() const
{
if (external_id == "") throw cRuntimeError("TraCIMobility::getExternalId called with no external_id set yet");
return external_id;
}
virtual double getHostPositionOffset() const
{
return hostPositionOffset;
}
virtual bool getParkingState() const
{
return isParking;
}
virtual std::string getRoadId() const
{
if (road_id == "") throw cRuntimeError("TraCIMobility::getRoadId called with no road_id set yet");
return road_id;
}
virtual double getSpeed() const
{
if (speed == -1) throw cRuntimeError("TraCIMobility::getSpeed called with no speed set yet");
return speed;
}
virtual VehicleSignalSet getSignals() const
{
if (signals.test(VehicleSignal::undefined)) throw cRuntimeError("TraCIMobility::getSignals called with no signals set yet");
return signals;
}
/**
* returns heading.
*/
virtual Heading getHeading() const
{
if (heading.isNan()) throw cRuntimeError("TraCIMobility::getHeading called with no heading set yet");
return heading;
}
virtual TraCIScenarioManager* getManager() const
{
if (!manager) manager = TraCIScenarioManagerAccess().get();
return manager;
}
virtual TraCICommandInterface* getCommandInterface() const
{
if (!commandInterface) commandInterface = getManager()->getCommandInterface();
return commandInterface;
}
virtual TraCICommandInterface::Vehicle* getVehicleCommandInterface() const
{
if (!vehicleCommandInterface) vehicleCommandInterface = new TraCICommandInterface::Vehicle(getCommandInterface()->vehicle(getExternalId()));
return vehicleCommandInterface;
}
/**
* Returns the speed of the host (likely 0 if setHostSpeed==false)
*/
Coord getHostSpeed() const
{
return BaseMobility::getCurrentSpeed();
}
protected:
int accidentCount; /**< number of accidents */
cOutVector currentPosXVec; /**< vector plotting posx */
cOutVector currentPosYVec; /**< vector plotting posy */
cOutVector currentSpeedVec; /**< vector plotting speed */
cOutVector currentAccelerationVec; /**< vector plotting acceleration */
cOutVector currentCO2EmissionVec; /**< vector plotting current CO2 emission */
Statistics statistics; /**< everything statistics-related */
bool isPreInitialized; /**< true if preInitialize() has been called immediately before initialize() */
std::string external_id; /**< updated by setExternalId() */
double hostPositionOffset; /**< front offset for the antenna on this car */
bool setHostSpeed; /**< whether to update the speed of the host (along with its position) */
simtime_t lastUpdate; /**< updated by nextPosition() */
Coord roadPosition; /**< position of front bumper, updated by nextPosition() */
std::string road_id; /**< updated by nextPosition() */
double speed; /**< updated by nextPosition() */
Heading heading; /**< updated by nextPosition() */
VehicleSignalSet signals; /**<updated by nextPosition() */
cMessage* startAccidentMsg;
cMessage* stopAccidentMsg;
mutable TraCIScenarioManager* manager;
mutable TraCICommandInterface* commandInterface;
mutable TraCICommandInterface::Vehicle* vehicleCommandInterface;
double last_speed;
bool isParking;
void fixIfHostGetsOutside() override; /**< called after each read to check for (and handle) invalid positions */
/**
* Returns the amount of CO2 emissions in grams/second, calculated for an average Car
* @param v speed in m/s
* @param a acceleration in m/s^2
* @returns emission in g/s
*/
double calculateCO2emission(double v, double a) const;
/**
* Calculates where the OMNeT++ module position of this car should be, given its front bumper position
*/
Coord calculateHostPosition(const Coord& vehiclePos) const;
/**
* Calling this method on pointers of type TraCIMobility is deprecated in favor of calling either getHostSpeed or getSpeed.
*/
Coord getCurrentSpeed() const override
{
return BaseMobility::getCurrentSpeed();
}
};
class VEINS_API TraCIMobilityAccess {
public:
TraCIMobility* get(cModule* host)
{
TraCIMobility* traci = FindModule<TraCIMobility*>::findSubModule(host);
ASSERT(traci);
return traci;
};
};
} // namespace veins
| 8,475 | 35.692641 | 185 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIRegionOfInterest.cc | //
// Copyright (C) 2015 Raphael Riebl <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <algorithm>
#include <sstream>
#include "veins/veins.h"
#include "veins/modules/mobility/traci/TraCIRegionOfInterest.h"
namespace veins {
TraCIRegionOfInterest::TraCIRegionOfInterest()
{
}
void TraCIRegionOfInterest::addRoads(const std::string& roads)
{
std::istringstream roadsStream(roads);
std::string road;
while (std::getline(roadsStream, road, ' ')) {
roiRoads.insert(road);
}
}
void TraCIRegionOfInterest::addRectangles(const std::string& rects)
{
std::istringstream rectsStream(rects);
std::string rect;
while (std::getline(rectsStream, rect, ' ')) {
std::istringstream rectStream(rect);
double x1;
rectStream >> x1;
char c1;
rectStream >> c1;
double y1;
rectStream >> y1;
char c2;
rectStream >> c2;
double x2;
rectStream >> x2;
char c3;
rectStream >> c3;
double y2;
rectStream >> y2;
if (rectStream.good()) {
throw cRuntimeError("Parsing ROI rectangle failed");
}
roiRects.push_back(std::pair<TraCICoord, TraCICoord>(TraCICoord(x1, y1), TraCICoord(x2, y2)));
}
}
void TraCIRegionOfInterest::clear()
{
roiRoads.clear();
roiRects.clear();
}
bool TraCIRegionOfInterest::onAnyRectangle(const TraCICoord& position) const
{
struct RectangleTest {
RectangleTest(const TraCICoord& position_)
: position(position_)
{
}
bool operator()(const std::pair<TraCICoord, TraCICoord>& rect) const
{
return (position.x >= rect.first.x && position.y >= rect.first.y) && (position.x <= rect.second.x && position.y <= rect.second.y);
}
const TraCICoord& position;
};
std::list<std::pair<TraCICoord, TraCICoord>>::const_iterator found = std::find_if(roiRects.begin(), roiRects.end(), RectangleTest(position));
return found != roiRects.end();
}
bool TraCIRegionOfInterest::partOfRoads(const std::string& road) const
{
return roiRoads.count(road) > 0;
}
bool TraCIRegionOfInterest::hasConstraints() const
{
return !roiRoads.empty() || !roiRects.empty();
}
const std::list<std::pair<TraCICoord, TraCICoord>>& TraCIRegionOfInterest::getRectangles() const
{
return roiRects;
}
} // namespace veins
| 3,213 | 27.192982 | 145 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIRegionOfInterest.h | //
// Copyright (C) 2015 Raphael Riebl <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <list>
#include <set>
#include <string>
#include <utility>
#include "veins/modules/mobility/traci/TraCICoord.h"
namespace veins {
/**
* Can return whether a given position lies within the simulation's region of interest.
* Modules are destroyed and re-created as managed vehicles leave and re-enter the ROI
*/
class VEINS_API TraCIRegionOfInterest {
public:
enum ConstraintResult {
NONE, // when no constraints exist
SATISFY,
BREAK
};
TraCIRegionOfInterest();
/**
* Add roads to contraints
* @param roads given as road ids separated by spaces
*/
void addRoads(const std::string& roads);
/**
* Add rectangles to constraints
* @param rects given as x1,y1-x2,y2 pairs separated by spaces
*/
void addRectangles(const std::string& rects);
/**
* Remove all constraints
*/
void clear();
/**
* Check if position lies on any ROI rectangle
* @param pos Position to check
* @return true if on any rectangle
*/
bool onAnyRectangle(const TraCICoord& pos) const;
/**
* Check if a given road is part of interest roads
* @param road_id
* @return true if part of ROI roads
*/
bool partOfRoads(const std::string& road_id) const;
/**
* Check if any constraints are defined
* @return true if constraints exist
*/
bool hasConstraints() const;
const std::list<std::pair<TraCICoord, TraCICoord>>& getRectangles() const;
private:
std::set<std::string> roiRoads; /**< which roads (e.g. "hwy1 hwy2") are considered to consitute the region of interest, if not empty */
std::list<std::pair<TraCICoord, TraCICoord>> roiRects; /**< which rectangles (e.g. "0,0-10,10 20,20-30,30) are considered to consitute the region of interest, if not empty */
};
} // namespace veins
| 2,769 | 28.784946 | 178 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManager.cc | //
// Copyright (C) 2006-2017 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iterator>
#include <cstdlib>
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/base/connectionManager/ChannelAccess.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/TraCIMobility.h"
#include "veins/modules/obstacle/ObstacleControl.h"
#include "veins/modules/world/traci/trafficLight/TraCITrafficLightInterface.h"
using namespace veins::TraCIConstants;
using veins::AnnotationManagerAccess;
using veins::TraCIBuffer;
using veins::TraCICoord;
using veins::TraCIScenarioManager;
using veins::TraCITrafficLightInterface;
Define_Module(veins::TraCIScenarioManager);
const simsignal_t TraCIScenarioManager::traciInitializedSignal = registerSignal("org_car2x_veins_modules_mobility_traciInitialized");
const simsignal_t TraCIScenarioManager::traciModuleAddedSignal = registerSignal("org_car2x_veins_modules_mobility_traciModuleAdded");
const simsignal_t TraCIScenarioManager::traciModuleRemovedSignal = registerSignal("org_car2x_veins_modules_mobility_traciModuleRemoved");
const simsignal_t TraCIScenarioManager::traciTimestepBeginSignal = registerSignal("org_car2x_veins_modules_mobility_traciTimestepBegin");
const simsignal_t TraCIScenarioManager::traciTimestepEndSignal = registerSignal("org_car2x_veins_modules_mobility_traciTimestepEnd");
TraCIScenarioManager::TraCIScenarioManager()
: connection(nullptr)
, commandIfc(nullptr)
, connectAndStartTrigger(nullptr)
, executeOneTimestepTrigger(nullptr)
, world(nullptr)
{
}
TraCIScenarioManager::~TraCIScenarioManager()
{
if (connection) {
TraCIBuffer buf = connection->query(CMD_CLOSE, TraCIBuffer());
}
cancelAndDelete(connectAndStartTrigger);
cancelAndDelete(executeOneTimestepTrigger);
}
namespace {
std::vector<std::string> getMapping(std::string el)
{
// search for string protection characters '
char protection = '\'';
size_t first = el.find(protection);
size_t second;
size_t eq;
std::string type, value;
std::vector<std::string> mapping;
if (first == std::string::npos) {
// there's no string protection, simply split by '='
cStringTokenizer stk(el.c_str(), "=");
mapping = stk.asVector();
}
else {
// if there's string protection, we need to find a matching delimiter
second = el.find(protection, first + 1);
// ensure that a matching delimiter exists, and that it is at the end
if (second == std::string::npos || second != el.size() - 1) throw cRuntimeError("invalid syntax for mapping \"%s\"", el.c_str());
// take the value of the mapping as the text within the quotes
value = el.substr(first + 1, second - first - 1);
if (first == 0) {
// if the string starts with a quote, there's only the value
mapping.push_back(value);
}
else {
// search for the equal sign
eq = el.find('=');
// this must be the character before the quote
if (eq == std::string::npos || eq != first - 1) {
throw cRuntimeError("invalid syntax for mapping \"%s\"", el.c_str());
}
else {
type = el.substr(0, eq);
}
mapping.push_back(type);
mapping.push_back(value);
}
}
return mapping;
}
} // namespace
TraCIScenarioManager::TypeMapping TraCIScenarioManager::parseMappings(std::string parameter, std::string parameterName, bool allowEmpty)
{
/**
* possible syntaxes
*
* "a" : assign module type "a" to all nodes (for backward compatibility)
* "a=b" : assign module type "b" to vehicle type "a". the presence of any other vehicle type in the simulation will cause the simulation to stop
* "a=b c=d" : assign module type "b" to vehicle type "a" and "d" to "c". the presence of any other vehicle type in the simulation will cause the simulation to stop
* "a=b c=d *=e": everything which is not of vehicle type "a" or "b", assign module type "e"
* "a=b c=0" : for vehicle type "c" no module should be instantiated
* "a=b c=d *=0": everything which is not of vehicle type a or c should not be instantiated
*
* For display strings key-value pairs needs to be protected with single quotes, as they use an = sign as the type mappings. For example
* *.manager.moduleDisplayString = "'i=block/process'"
* *.manager.moduleDisplayString = "a='i=block/process' b='i=misc/sun'"
*
* moduleDisplayString can also be left empty:
* *.manager.moduleDisplayString = ""
*/
unsigned int i;
TypeMapping map;
// tokenizer to split into mappings ("a=b c=d", -> ["a=b", "c=d"])
cStringTokenizer typesTz(parameter.c_str(), " ");
// get all mappings
std::vector<std::string> typeMappings = typesTz.asVector();
// and check that there exists at least one
if (typeMappings.size() == 0) {
if (!allowEmpty)
throw cRuntimeError("parameter \"%s\" is empty", parameterName.c_str());
else
return map;
}
// loop through all mappings
for (i = 0; i < typeMappings.size(); i++) {
// tokenizer to find the mapping from vehicle type to module type
std::string typeMapping = typeMappings[i];
std::vector<std::string> mapping = getMapping(typeMapping);
if (mapping.size() == 1) {
// we are where there is no actual assignment
// "a": this is good
// "a b=c": this is not
if (typeMappings.size() != 1)
// stop simulation with an error
throw cRuntimeError("parameter \"%s\" includes multiple mappings, but \"%s\" is not mapped to any vehicle type", parameterName.c_str(), mapping[0].c_str());
else
// all vehicle types should be instantiated with this module type
map["*"] = mapping[0];
}
else {
// check that mapping is valid (a=b and not like a=b=c)
if (mapping.size() != 2) throw cRuntimeError("invalid syntax for mapping \"%s\" for parameter \"%s\"", typeMapping.c_str(), parameterName.c_str());
// check that the mapping does not already exist
if (map.find(mapping[0]) != map.end()) throw cRuntimeError("duplicated mapping for vehicle type \"%s\" for parameter \"%s\"", mapping[0].c_str(), parameterName.c_str());
// finally save the mapping
map[mapping[0]] = mapping[1];
}
}
return map;
}
void TraCIScenarioManager::parseModuleTypes()
{
TypeMapping::iterator i;
std::vector<std::string> typeKeys, nameKeys, displayStringKeys;
std::string moduleTypes = par("moduleType").stdstringValue();
std::string moduleNames = par("moduleName").stdstringValue();
std::string moduleDisplayStrings = par("moduleDisplayString").stdstringValue();
moduleType = parseMappings(moduleTypes, "moduleType", false);
moduleName = parseMappings(moduleNames, "moduleName", false);
moduleDisplayString = parseMappings(moduleDisplayStrings, "moduleDisplayString", true);
// perform consistency check. for each vehicle type in moduleType there must be a vehicle type
// in moduleName (and in moduleDisplayString if moduleDisplayString is not empty)
// get all the keys
for (i = moduleType.begin(); i != moduleType.end(); i++) typeKeys.push_back(i->first);
for (i = moduleName.begin(); i != moduleName.end(); i++) nameKeys.push_back(i->first);
for (i = moduleDisplayString.begin(); i != moduleDisplayString.end(); i++) displayStringKeys.push_back(i->first);
// sort them (needed for intersection)
std::sort(typeKeys.begin(), typeKeys.end());
std::sort(nameKeys.begin(), nameKeys.end());
std::sort(displayStringKeys.begin(), displayStringKeys.end());
std::vector<std::string> intersection;
// perform set intersection
std::set_intersection(typeKeys.begin(), typeKeys.end(), nameKeys.begin(), nameKeys.end(), std::back_inserter(intersection));
if (intersection.size() != typeKeys.size() || intersection.size() != nameKeys.size()) throw cRuntimeError("keys of mappings of moduleType and moduleName are not the same");
if (displayStringKeys.size() == 0) return;
intersection.clear();
std::set_intersection(typeKeys.begin(), typeKeys.end(), displayStringKeys.begin(), displayStringKeys.end(), std::back_inserter(intersection));
if (intersection.size() != displayStringKeys.size()) throw cRuntimeError("keys of mappings of moduleType and moduleName are not the same");
}
void TraCIScenarioManager::initialize(int stage)
{
cSimpleModule::initialize(stage);
if (stage != 1) {
return;
}
trafficLightModuleType = par("trafficLightModuleType").stdstringValue();
trafficLightModuleName = par("trafficLightModuleName").stdstringValue();
trafficLightModuleDisplayString = par("trafficLightModuleDisplayString").stdstringValue();
trafficLightModuleIds.clear();
std::istringstream filterstream(par("trafficLightFilter").stdstringValue());
std::copy(std::istream_iterator<std::string>(filterstream), std::istream_iterator<std::string>(), std::back_inserter(trafficLightModuleIds));
connectAt = par("connectAt");
firstStepAt = par("firstStepAt");
updateInterval = par("updateInterval");
if (firstStepAt == -1) firstStepAt = connectAt + updateInterval;
parseModuleTypes();
penetrationRate = par("penetrationRate").doubleValue();
ignoreGuiCommands = par("ignoreGuiCommands");
host = par("host").stdstringValue();
port = getPortNumber();
if (port == -1) {
throw cRuntimeError("TraCI Port autoconfiguration failed, set 'port' != -1 in omnetpp.ini or provide VEINS_TRACI_PORT environment variable.");
}
autoShutdown = par("autoShutdown");
annotations = AnnotationManagerAccess().getIfExists();
roi.clear();
roi.addRoads(par("roiRoads"));
roi.addRectangles(par("roiRects"));
areaSum = 0;
nextNodeVectorIndex = 0;
hosts.clear();
subscribedVehicles.clear();
trafficLights.clear();
activeVehicleCount = 0;
parkingVehicleCount = 0;
drivingVehicleCount = 0;
autoShutdownTriggered = false;
world = FindModule<BaseWorldUtility*>::findGlobalModule();
vehicleObstacleControl = FindModule<VehicleObstacleControl*>::findGlobalModule();
ASSERT(firstStepAt > connectAt);
connectAndStartTrigger = new cMessage("connect");
scheduleAt(connectAt, connectAndStartTrigger);
executeOneTimestepTrigger = new cMessage("step");
scheduleAt(firstStepAt, executeOneTimestepTrigger);
EV_DEBUG << "initialized TraCIScenarioManager" << endl;
}
void TraCIScenarioManager::init_traci()
{
auto* commandInterface = getCommandInterface();
{
auto apiVersion = commandInterface->getVersion();
EV_DEBUG << "TraCI server \"" << apiVersion.second << "\" reports API version " << apiVersion.first << endl;
commandInterface->setApiVersion(apiVersion.first);
}
{
// query and set road network boundaries
auto networkBoundaries = commandInterface->initNetworkBoundaries(par("margin"));
if (world != nullptr && ((connection->traci2omnet(networkBoundaries.second).x > world->getPgs()->x) || (connection->traci2omnet(networkBoundaries.first).y > world->getPgs()->y))) {
EV_DEBUG << "WARNING: Playground size (" << world->getPgs()->x << ", " << world->getPgs()->y << ") might be too small for vehicle at network bounds (" << connection->traci2omnet(networkBoundaries.second).x << ", " << connection->traci2omnet(networkBoundaries.first).y << ")" << endl;
}
}
{
// subscribe to list of departed and arrived vehicles, as well as simulation time
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = "";
uint8_t variableNumber = 7;
uint8_t variable1 = VAR_DEPARTED_VEHICLES_IDS;
uint8_t variable2 = VAR_ARRIVED_VEHICLES_IDS;
uint8_t variable3 = commandInterface->getTimeStepCmd();
uint8_t variable4 = VAR_TELEPORT_STARTING_VEHICLES_IDS;
uint8_t variable5 = VAR_TELEPORT_ENDING_VEHICLES_IDS;
uint8_t variable6 = VAR_PARKING_STARTING_VEHICLES_IDS;
uint8_t variable7 = VAR_PARKING_ENDING_VEHICLES_IDS;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_SIM_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4 << variable5 << variable6 << variable7);
processSubcriptionResult(buf);
ASSERT(buf.eof());
}
{
// subscribe to list of vehicle ids
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = "";
uint8_t variableNumber = 1;
uint8_t variable1 = ID_LIST;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1);
processSubcriptionResult(buf);
ASSERT(buf.eof());
}
if (!trafficLightModuleType.empty() && !trafficLightModuleIds.empty()) {
// initialize traffic lights
cModule* parentmod = getParentModule();
if (!parentmod) {
throw cRuntimeError("Parent Module not found (for traffic light creation)");
}
cModuleType* tlModuleType = cModuleType::get(trafficLightModuleType.c_str());
// query traffic lights via TraCI
std::list<std::string> trafficLightIds = commandInterface->getTrafficlightIds();
size_t nrOfTrafficLights = trafficLightIds.size();
int cnt = 0;
for (std::list<std::string>::iterator i = trafficLightIds.begin(); i != trafficLightIds.end(); ++i) {
std::string tlId = *i;
if (std::find(trafficLightModuleIds.begin(), trafficLightModuleIds.end(), tlId) == trafficLightModuleIds.end()) {
continue; // filter only selected elements
}
Coord position = commandInterface->junction(tlId).getPosition();
cModule* module = tlModuleType->create(trafficLightModuleName.c_str(), parentmod, nrOfTrafficLights, cnt);
module->par("externalId") = tlId;
module->finalizeParameters();
module->getDisplayString().parse(trafficLightModuleDisplayString.c_str());
module->buildInside();
module->scheduleStart(simTime() + updateInterval);
cModule* tlIfSubmodule = module->getSubmodule("tlInterface");
// initialize traffic light interface with current program
TraCITrafficLightInterface* tlIfModule = dynamic_cast<TraCITrafficLightInterface*>(tlIfSubmodule);
tlIfModule->preInitialize(tlId, position, updateInterval);
// initialize mobility for positioning
cModule* mobiSubmodule = module->getSubmodule("mobility");
mobiSubmodule->par("x") = position.x;
mobiSubmodule->par("y") = position.y;
mobiSubmodule->par("z") = position.z;
module->callInitialize();
trafficLights[tlId] = module;
subscribeToTrafficLightVariables(tlId); // subscribe after module is in trafficLights
cnt++;
}
}
ObstacleControl* obstacles = ObstacleControlAccess().getIfExists();
if (obstacles) {
{
// get list of polygons
std::list<std::string> ids = commandInterface->getPolygonIds();
for (std::list<std::string>::iterator i = ids.begin(); i != ids.end(); ++i) {
std::string id = *i;
std::string typeId = commandInterface->polygon(id).getTypeId();
if (!obstacles->isTypeSupported(typeId)) continue;
std::list<Coord> coords = commandInterface->polygon(id).getShape();
std::vector<Coord> shape;
std::copy(coords.begin(), coords.end(), std::back_inserter(shape));
obstacles->addFromTypeAndShape(id, typeId, shape);
}
}
}
traciInitialized = true;
emit(traciInitializedSignal, true);
// draw and calculate area of rois
for (std::list<std::pair<TraCICoord, TraCICoord>>::const_iterator r = roi.getRectangles().begin(), end = roi.getRectangles().end(); r != end; ++r) {
TraCICoord first = r->first;
TraCICoord second = r->second;
std::list<Coord> pol;
Coord a = connection->traci2omnet(first);
Coord b = connection->traci2omnet(TraCICoord(first.x, second.y));
Coord c = connection->traci2omnet(second);
Coord d = connection->traci2omnet(TraCICoord(second.x, first.y));
pol.push_back(a);
pol.push_back(b);
pol.push_back(c);
pol.push_back(d);
// draw polygon for region of interest
if (annotations) {
annotations->drawPolygon(pol, "black");
}
// calculate region area
double ab = a.distance(b);
double ad = a.distance(d);
double area = ab * ad;
areaSum += area;
}
}
void TraCIScenarioManager::finish()
{
while (hosts.begin() != hosts.end()) {
deleteManagedModule(hosts.begin()->first);
}
recordScalar("roiArea", areaSum);
}
void TraCIScenarioManager::handleMessage(cMessage* msg)
{
if (msg->isSelfMessage()) {
handleSelfMsg(msg);
return;
}
throw cRuntimeError("TraCIScenarioManager doesn't handle messages from other modules");
}
void TraCIScenarioManager::handleSelfMsg(cMessage* msg)
{
if (msg == connectAndStartTrigger) {
connection.reset(TraCIConnection::connect(this, host.c_str(), port));
commandIfc.reset(new TraCICommandInterface(this, *connection, ignoreGuiCommands));
init_traci();
return;
}
if (msg == executeOneTimestepTrigger) {
executeOneTimestep();
return;
}
throw cRuntimeError("TraCIScenarioManager received unknown self-message");
}
void TraCIScenarioManager::preInitializeModule(cModule* mod, const std::string& nodeId, const Coord& position, const std::string& road_id, double speed, Heading heading, VehicleSignalSet signals)
{
// pre-initialize TraCIMobility
auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod);
for (auto mm : mobilityModules) {
mm->preInitialize(nodeId, position, road_id, speed, heading);
}
}
void TraCIScenarioManager::updateModulePosition(cModule* mod, const Coord& p, const std::string& edge, double speed, Heading heading, VehicleSignalSet signals)
{
// update position in TraCIMobility
auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod);
for (auto mm : mobilityModules) {
mm->nextPosition(p, edge, speed, heading, signals);
}
}
// name: host;Car;i=vehicle.gif
void TraCIScenarioManager::addModule(std::string nodeId, std::string type, std::string name, std::string displayString, const Coord& position, std::string road_id, double speed, Heading heading, VehicleSignalSet signals, double length, double height, double width)
{
if (hosts.find(nodeId) != hosts.end()) throw cRuntimeError("tried adding duplicate module");
double option1 = hosts.size() / (hosts.size() + unEquippedHosts.size() + 1.0);
double option2 = (hosts.size() + 1) / (hosts.size() + unEquippedHosts.size() + 1.0);
if (fabs(option1 - penetrationRate) < fabs(option2 - penetrationRate)) {
unEquippedHosts.insert(nodeId);
return;
}
int32_t nodeVectorIndex = nextNodeVectorIndex++;
cModule* parentmod = getParentModule();
if (!parentmod) throw cRuntimeError("Parent Module not found");
cModuleType* nodeType = cModuleType::get(type.c_str());
if (!nodeType) throw cRuntimeError("Module Type \"%s\" not found", type.c_str());
// TODO: this trashes the vectsize member of the cModule, although nobody seems to use it
cModule* mod = nodeType->create(name.c_str(), parentmod, nodeVectorIndex, nodeVectorIndex);
mod->finalizeParameters();
if (displayString.length() > 0) {
mod->getDisplayString().parse(displayString.c_str());
}
mod->buildInside();
mod->scheduleStart(simTime() + updateInterval);
preInitializeModule(mod, nodeId, position, road_id, speed, heading, signals);
mod->callInitialize();
hosts[nodeId] = mod;
// post-initialize TraCIMobility
auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod);
for (auto mm : mobilityModules) {
mm->changePosition();
}
if (vehicleObstacleControl) {
std::vector<AntennaPosition> initialAntennaPositions;
for (auto& caModule : getSubmodulesOfType<ChannelAccess>(mod, true)) {
initialAntennaPositions.push_back(caModule->getAntennaPosition());
}
ASSERT(mobilityModules.size() == 1);
auto mm = mobilityModules[0];
double offset = mm->getHostPositionOffset();
const MobileHostObstacle* vo = vehicleObstacleControl->add(MobileHostObstacle(initialAntennaPositions, mm, length, offset, width, height));
vehicleObstacles[mm] = vo;
}
emit(traciModuleAddedSignal, mod);
}
cModule* TraCIScenarioManager::getManagedModule(std::string nodeId)
{
if (hosts.find(nodeId) == hosts.end()) return nullptr;
return hosts[nodeId];
}
bool TraCIScenarioManager::isModuleUnequipped(std::string nodeId)
{
if (unEquippedHosts.find(nodeId) == unEquippedHosts.end()) return false;
return true;
}
void TraCIScenarioManager::deleteManagedModule(std::string nodeId)
{
cModule* mod = getManagedModule(nodeId);
if (!mod) throw cRuntimeError("no vehicle with Id \"%s\" found", nodeId.c_str());
emit(traciModuleRemovedSignal, mod);
auto cas = getSubmodulesOfType<ChannelAccess>(mod, true);
for (auto ca : cas) {
cModule* nic = ca->getParentModule();
auto connectionManager = ChannelAccess::getConnectionManager(nic);
connectionManager->unregisterNic(nic);
}
if (vehicleObstacleControl) {
for (cModule::SubmoduleIterator iter(mod); !iter.end(); iter++) {
cModule* submod = *iter;
TraCIMobility* mm = dynamic_cast<TraCIMobility*>(submod);
if (!mm) continue;
auto vo = vehicleObstacles.find(mm);
ASSERT(vo != vehicleObstacles.end());
vehicleObstacleControl->erase(vo->second);
}
}
hosts.erase(nodeId);
mod->callFinish();
mod->deleteModule();
}
void TraCIScenarioManager::executeOneTimestep()
{
EV_DEBUG << "Triggering TraCI server simulation advance to t=" << simTime() << endl;
simtime_t targetTime = simTime();
emit(traciTimestepBeginSignal, targetTime);
if (isConnected()) {
TraCIBuffer buf = connection->query(CMD_SIMSTEP2, TraCIBuffer() << targetTime);
uint32_t count;
buf >> count;
EV_DEBUG << "Getting " << count << " subscription results" << endl;
for (uint32_t i = 0; i < count; ++i) {
processSubcriptionResult(buf);
}
}
emit(traciTimestepEndSignal, targetTime);
if (!autoShutdownTriggered) scheduleAt(simTime() + updateInterval, executeOneTimestepTrigger);
}
void TraCIScenarioManager::subscribeToVehicleVariables(std::string vehicleId)
{
// subscribe to some attributes of the vehicle
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = vehicleId;
uint8_t variableNumber = 8;
uint8_t variable1 = VAR_POSITION;
uint8_t variable2 = VAR_ROAD_ID;
uint8_t variable3 = VAR_SPEED;
uint8_t variable4 = VAR_ANGLE;
uint8_t variable5 = VAR_SIGNALS;
uint8_t variable6 = VAR_LENGTH;
uint8_t variable7 = VAR_HEIGHT;
uint8_t variable8 = VAR_WIDTH;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4 << variable5 << variable6 << variable7 << variable8);
processSubcriptionResult(buf);
ASSERT(buf.eof());
}
void TraCIScenarioManager::unsubscribeFromVehicleVariables(std::string vehicleId)
{
// subscribe to some attributes of the vehicle
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = vehicleId;
uint8_t variableNumber = 0;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_VEHICLE_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber);
ASSERT(buf.eof());
}
void TraCIScenarioManager::subscribeToTrafficLightVariables(std::string tlId)
{
// subscribe to some attributes of the traffic light system
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = tlId;
uint8_t variableNumber = 4;
uint8_t variable1 = TL_CURRENT_PHASE;
uint8_t variable2 = TL_CURRENT_PROGRAM;
uint8_t variable3 = TL_NEXT_SWITCH;
uint8_t variable4 = TL_RED_YELLOW_GREEN_STATE;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_TL_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber << variable1 << variable2 << variable3 << variable4);
processSubcriptionResult(buf);
ASSERT(buf.eof());
}
void TraCIScenarioManager::unsubscribeFromTrafficLightVariables(std::string tlId)
{
// unsubscribe from some attributes of the traffic light system
// this method is mainly for completeness as traffic lights are not supposed to be removed at runtime
simtime_t beginTime = 0;
simtime_t endTime = SimTime::getMaxTime();
std::string objectId = tlId;
uint8_t variableNumber = 0;
TraCIBuffer buf = connection->query(CMD_SUBSCRIBE_TL_VARIABLE, TraCIBuffer() << beginTime << endTime << objectId << variableNumber);
ASSERT(buf.eof());
}
void TraCIScenarioManager::processTrafficLightSubscription(std::string objectId, TraCIBuffer& buf)
{
cModule* tlIfSubmodule = trafficLights[objectId]->getSubmodule("tlInterface");
TraCITrafficLightInterface* tlIfModule = dynamic_cast<TraCITrafficLightInterface*>(tlIfSubmodule);
if (!tlIfModule) {
throw cRuntimeError("Could not find traffic light module %s", objectId.c_str());
}
uint8_t variableNumber_resp;
buf >> variableNumber_resp;
for (uint8_t j = 0; j < variableNumber_resp; ++j) {
uint8_t response_type;
buf >> response_type;
uint8_t isokay;
buf >> isokay;
if (isokay != RTYPE_OK) {
std::string description = buf.readTypeChecked<std::string>(TYPE_STRING);
if (isokay == RTYPE_NOTIMPLEMENTED) {
throw cRuntimeError("TraCI server reported subscribing to 0x%2x not implemented (\"%s\"). Might need newer version.", response_type, description.c_str());
}
else {
throw cRuntimeError("TraCI server reported error subscribing to variable 0x%2x (\"%s\").", response_type, description.c_str());
}
}
switch (response_type) {
case TL_CURRENT_PHASE:
tlIfModule->setCurrentPhaseByNr(buf.readTypeChecked<int32_t>(TYPE_INTEGER), false);
break;
case TL_CURRENT_PROGRAM:
tlIfModule->setCurrentLogicById(buf.readTypeChecked<std::string>(TYPE_STRING), false);
break;
case TL_NEXT_SWITCH:
tlIfModule->setNextSwitch(buf.readTypeChecked<simtime_t>(getCommandInterface()->getTimeType()), false);
break;
case TL_RED_YELLOW_GREEN_STATE:
tlIfModule->setCurrentState(buf.readTypeChecked<std::string>(TYPE_STRING), false);
break;
default:
throw cRuntimeError("Received unhandled traffic light subscription result; type: 0x%02x", response_type);
break;
}
}
}
void TraCIScenarioManager::processSimSubscription(std::string objectId, TraCIBuffer& buf)
{
uint8_t variableNumber_resp;
buf >> variableNumber_resp;
for (uint8_t j = 0; j < variableNumber_resp; ++j) {
uint8_t variable1_resp;
buf >> variable1_resp;
uint8_t isokay;
buf >> isokay;
if (isokay != RTYPE_OK) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRING);
std::string description;
buf >> description;
if (isokay == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported subscribing to variable 0x%2x not implemented (\"%s\"). Might need newer version.", variable1_resp, description.c_str());
throw cRuntimeError("TraCI server reported error subscribing to variable 0x%2x (\"%s\").", variable1_resp, description.c_str());
}
if (variable1_resp == VAR_DEPARTED_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " departed vehicles." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
// adding modules is handled on the fly when entering/leaving the ROI
}
activeVehicleCount += count;
drivingVehicleCount += count;
}
else if (variable1_resp == VAR_ARRIVED_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " arrived vehicles." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
if (subscribedVehicles.find(idstring) != subscribedVehicles.end()) {
subscribedVehicles.erase(idstring);
// no unsubscription via TraCI possible/necessary as of SUMO 1.0.0 (the vehicle has arrived)
}
// check if this object has been deleted already (e.g. because it was outside the ROI)
cModule* mod = getManagedModule(idstring);
if (mod) deleteManagedModule(idstring);
if (unEquippedHosts.find(idstring) != unEquippedHosts.end()) {
unEquippedHosts.erase(idstring);
}
}
if ((count > 0) && (count >= activeVehicleCount) && autoShutdown) autoShutdownTriggered = true;
activeVehicleCount -= count;
drivingVehicleCount -= count;
}
else if (variable1_resp == VAR_TELEPORT_STARTING_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " vehicles starting to teleport." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
// check if this object has been deleted already (e.g. because it was outside the ROI)
cModule* mod = getManagedModule(idstring);
if (mod) deleteManagedModule(idstring);
if (unEquippedHosts.find(idstring) != unEquippedHosts.end()) {
unEquippedHosts.erase(idstring);
}
}
activeVehicleCount -= count;
drivingVehicleCount -= count;
}
else if (variable1_resp == VAR_TELEPORT_ENDING_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " vehicles ending teleport." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
// adding modules is handled on the fly when entering/leaving the ROI
}
activeVehicleCount += count;
drivingVehicleCount += count;
}
else if (variable1_resp == VAR_PARKING_STARTING_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " vehicles starting to park." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
cModule* mod = getManagedModule(idstring);
auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod);
for (auto mm : mobilityModules) {
mm->changeParkingState(true);
}
}
parkingVehicleCount += count;
drivingVehicleCount -= count;
}
else if (variable1_resp == VAR_PARKING_ENDING_VEHICLES_IDS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " vehicles ending to park." << endl;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
cModule* mod = getManagedModule(idstring);
auto mobilityModules = getSubmodulesOfType<TraCIMobility>(mod);
for (auto mm : mobilityModules) {
mm->changeParkingState(false);
}
}
parkingVehicleCount -= count;
drivingVehicleCount += count;
}
else if (variable1_resp == getCommandInterface()->getTimeStepCmd()) {
uint8_t varType;
buf >> varType;
ASSERT(varType == getCommandInterface()->getTimeType());
simtime_t serverTimestep;
buf >> serverTimestep;
EV_DEBUG << "TraCI reports current time step as " << serverTimestep << "ms." << endl;
simtime_t omnetTimestep = simTime();
ASSERT(omnetTimestep == serverTimestep);
}
else {
throw cRuntimeError("Received unhandled sim subscription result");
}
}
}
void TraCIScenarioManager::processVehicleSubscription(std::string objectId, TraCIBuffer& buf)
{
bool isSubscribed = (subscribedVehicles.find(objectId) != subscribedVehicles.end());
double px;
double py;
std::string edge;
double speed;
double angle_traci;
int signals;
double length;
double height;
double width;
int numRead = 0;
uint8_t variableNumber_resp;
buf >> variableNumber_resp;
for (uint8_t j = 0; j < variableNumber_resp; ++j) {
uint8_t variable1_resp;
buf >> variable1_resp;
uint8_t isokay;
buf >> isokay;
if (isokay != RTYPE_OK) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRING);
std::string errormsg;
buf >> errormsg;
if (isSubscribed) {
if (isokay == RTYPE_NOTIMPLEMENTED) throw cRuntimeError("TraCI server reported subscribing to vehicle variable 0x%2x not implemented (\"%s\"). Might need newer version.", variable1_resp, errormsg.c_str());
throw cRuntimeError("TraCI server reported error subscribing to vehicle variable 0x%2x (\"%s\").", variable1_resp, errormsg.c_str());
}
}
else if (variable1_resp == ID_LIST) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRINGLIST);
uint32_t count;
buf >> count;
EV_DEBUG << "TraCI reports " << count << " active vehicles." << endl;
ASSERT(count == activeVehicleCount);
std::set<std::string> drivingVehicles;
for (uint32_t i = 0; i < count; ++i) {
std::string idstring;
buf >> idstring;
drivingVehicles.insert(idstring);
}
// check for vehicles that need subscribing to
std::set<std::string> needSubscribe;
std::set_difference(drivingVehicles.begin(), drivingVehicles.end(), subscribedVehicles.begin(), subscribedVehicles.end(), std::inserter(needSubscribe, needSubscribe.begin()));
for (std::set<std::string>::const_iterator i = needSubscribe.begin(); i != needSubscribe.end(); ++i) {
subscribedVehicles.insert(*i);
subscribeToVehicleVariables(*i);
}
// check for vehicles that need unsubscribing from
std::set<std::string> needUnsubscribe;
std::set_difference(subscribedVehicles.begin(), subscribedVehicles.end(), drivingVehicles.begin(), drivingVehicles.end(), std::inserter(needUnsubscribe, needUnsubscribe.begin()));
for (std::set<std::string>::const_iterator i = needUnsubscribe.begin(); i != needUnsubscribe.end(); ++i) {
subscribedVehicles.erase(*i);
unsubscribeFromVehicleVariables(*i);
}
}
else if (variable1_resp == VAR_POSITION) {
uint8_t varType;
buf >> varType;
ASSERT(varType == POSITION_2D);
buf >> px;
buf >> py;
numRead++;
}
else if (variable1_resp == VAR_ROAD_ID) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_STRING);
buf >> edge;
numRead++;
}
else if (variable1_resp == VAR_SPEED) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_DOUBLE);
buf >> speed;
numRead++;
}
else if (variable1_resp == VAR_ANGLE) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_DOUBLE);
buf >> angle_traci;
numRead++;
}
else if (variable1_resp == VAR_SIGNALS) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_INTEGER);
buf >> signals;
numRead++;
}
else if (variable1_resp == VAR_LENGTH) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_DOUBLE);
buf >> length;
numRead++;
}
else if (variable1_resp == VAR_HEIGHT) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_DOUBLE);
buf >> height;
numRead++;
}
else if (variable1_resp == VAR_WIDTH) {
uint8_t varType;
buf >> varType;
ASSERT(varType == TYPE_DOUBLE);
buf >> width;
numRead++;
}
else {
throw cRuntimeError("Received unhandled vehicle subscription result");
}
}
// bail out if we didn't want to receive these subscription results
if (!isSubscribed) return;
// make sure we got updates for all attributes
if (numRead != 8) return;
Coord p = connection->traci2omnet(TraCICoord(px, py));
if ((p.x < 0) || (p.y < 0)) throw cRuntimeError("received bad node position (%.2f, %.2f), translated to (%.2f, %.2f)", px, py, p.x, p.y);
Heading heading = connection->traci2omnetHeading(angle_traci);
cModule* mod = getManagedModule(objectId);
// is it in the ROI?
bool inRoi = !roi.hasConstraints() ? true : (roi.onAnyRectangle(TraCICoord(px, py)) || roi.partOfRoads(edge));
if (!inRoi) {
if (mod) {
deleteManagedModule(objectId);
EV_DEBUG << "Vehicle #" << objectId << " left region of interest" << endl;
}
else if (unEquippedHosts.find(objectId) != unEquippedHosts.end()) {
unEquippedHosts.erase(objectId);
EV_DEBUG << "Vehicle (unequipped) # " << objectId << " left region of interest" << endl;
}
return;
}
if (isModuleUnequipped(objectId)) {
return;
}
if (!mod) {
// no such module - need to create
std::string vType = commandIfc->vehicle(objectId).getTypeId();
std::string mType, mName, mDisplayString;
TypeMapping::iterator iType, iName, iDisplayString;
TypeMapping::iterator i;
iType = moduleType.find(vType);
if (iType == moduleType.end()) {
iType = moduleType.find("*");
if (iType == moduleType.end()) throw cRuntimeError("cannot find a module type for vehicle type \"%s\"", vType.c_str());
}
mType = iType->second;
// search for module name
iName = moduleName.find(vType);
if (iName == moduleName.end()) {
iName = moduleName.find(std::string("*"));
if (iName == moduleName.end()) throw cRuntimeError("cannot find a module name for vehicle type \"%s\"", vType.c_str());
}
mName = iName->second;
if (moduleDisplayString.size() != 0) {
iDisplayString = moduleDisplayString.find(vType);
if (iDisplayString == moduleDisplayString.end()) {
iDisplayString = moduleDisplayString.find("*");
if (iDisplayString == moduleDisplayString.end()) throw cRuntimeError("cannot find a module display string for vehicle type \"%s\"", vType.c_str());
}
mDisplayString = iDisplayString->second;
}
else {
mDisplayString = "";
}
if (mType != "0") {
addModule(objectId, mType, mName, mDisplayString, p, edge, speed, heading, VehicleSignalSet(signals), length, height, width);
EV_DEBUG << "Added vehicle #" << objectId << endl;
}
}
else {
// module existed - update position
EV_DEBUG << "module " << objectId << " moving to " << p.x << "," << p.y << endl;
updateModulePosition(mod, p, edge, speed, heading, VehicleSignalSet(signals));
}
}
void TraCIScenarioManager::processSubcriptionResult(TraCIBuffer& buf)
{
uint8_t cmdLength_resp;
buf >> cmdLength_resp;
uint32_t cmdLengthExt_resp;
buf >> cmdLengthExt_resp;
uint8_t commandId_resp;
buf >> commandId_resp;
std::string objectId_resp;
buf >> objectId_resp;
if (commandId_resp == RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE)
processVehicleSubscription(objectId_resp, buf);
else if (commandId_resp == RESPONSE_SUBSCRIBE_SIM_VARIABLE)
processSimSubscription(objectId_resp, buf);
else if (commandId_resp == RESPONSE_SUBSCRIBE_TL_VARIABLE)
processTrafficLightSubscription(objectId_resp, buf);
else {
throw cRuntimeError("Received unhandled subscription result");
}
}
int TraCIScenarioManager::getPortNumber() const
{
int port = par("port");
if (port != -1) {
return port;
}
// search for externally configured traci port
const char* env_port = std::getenv("VEINS_TRACI_PORT");
if (env_port != nullptr) {
port = std::atoi(env_port);
}
return port;
}
| 44,467 | 38.953279 | 295 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManager.h | //
// Copyright (C) 2006-2017 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <map>
#include <memory>
#include <list>
#include <queue>
#include "veins/veins.h"
#include "veins/base/utils/Coord.h"
#include "veins/base/modules/BaseWorldUtility.h"
#include "veins/base/connectionManager/BaseConnectionManager.h"
#include "veins/base/utils/FindModule.h"
#include "veins/modules/obstacle/ObstacleControl.h"
#include "veins/modules/obstacle/VehicleObstacleControl.h"
#include "veins/modules/mobility/traci/TraCIBuffer.h"
#include "veins/modules/mobility/traci/TraCIColor.h"
#include "veins/modules/mobility/traci/TraCIConnection.h"
#include "veins/modules/mobility/traci/TraCICoord.h"
#include "veins/modules/mobility/traci/VehicleSignal.h"
#include "veins/modules/mobility/traci/TraCIRegionOfInterest.h"
namespace veins {
class TraCICommandInterface;
class MobileHostObstacle;
/**
* @brief
* Creates and moves nodes controlled by a TraCI server.
*
* If the server is a SUMO road traffic simulation, you can use the
* TraCIScenarioManagerLaunchd module and sumo-launchd.py script instead.
*
* All nodes created thus must have a TraCIMobility submodule.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer, David Eckhoff, Falko Dressler, Zheng Yao, Tobias Mayer, Alvaro Torres Cortes, Luca Bedogni
*
* @see TraCIMobility
* @see TraCIScenarioManagerLaunchd
*
*/
class VEINS_API TraCIScenarioManager : public cSimpleModule {
public:
static const simsignal_t traciInitializedSignal;
static const simsignal_t traciModuleAddedSignal;
static const simsignal_t traciModuleRemovedSignal;
static const simsignal_t traciTimestepBeginSignal;
static const simsignal_t traciTimestepEndSignal;
TraCIScenarioManager();
~TraCIScenarioManager() override;
int numInitStages() const override
{
return std::max(cSimpleModule::numInitStages(), 2);
}
void initialize(int stage) override;
void finish() override;
void handleMessage(cMessage* msg) override;
virtual void handleSelfMsg(cMessage* msg);
bool isConnected() const
{
return static_cast<bool>(connection);
}
TraCICommandInterface* getCommandInterface() const
{
return commandIfc.get();
}
TraCIConnection* getConnection() const
{
return connection.get();
}
bool getAutoShutdownTriggered()
{
return autoShutdownTriggered;
}
const std::map<std::string, cModule*>& getManagedHosts()
{
return hosts;
}
/**
* Predicate indicating a successful connection to the TraCI server.
*
* @note Once the connection has been established, this will return true even when the connection has been torn down again.
*/
bool isUsable() const
{
return traciInitialized;
}
protected:
bool traciInitialized = false; /**< Flag indicating whether the init_traci routine has been run. Note that it will change to false again once set, even during shutdown. */
simtime_t connectAt; /**< when to connect to TraCI server (must be the initial timestep of the server) */
simtime_t firstStepAt; /**< when to start synchronizing with the TraCI server (-1: immediately after connecting) */
simtime_t updateInterval; /**< time interval of hosts' position updates */
// maps from vehicle type to moduleType, moduleName, and moduleDisplayString
typedef std::map<std::string, std::string> TypeMapping;
TypeMapping moduleType; /**< module type to be used in the simulation for each managed vehicle */
TypeMapping moduleName; /**< module name to be used in the simulation for each managed vehicle */
TypeMapping moduleDisplayString; /**< module displayString to be used in the simulation for each managed vehicle */
std::string host;
int port;
std::string trafficLightModuleType; /**< module type to be used in the simulation for each managed traffic light */
std::string trafficLightModuleName; /**< module name to be used in the simulation for each managed traffic light */
std::string trafficLightModuleDisplayString; /**< module displayString to be used in the simulation for each managed vehicle */
std::vector<std::string> trafficLightModuleIds; /**< list of traffic light module ids that is subscribed to (whitelist) */
bool autoShutdown; /**< Shutdown module as soon as no more vehicles are in the simulation */
double penetrationRate;
bool ignoreGuiCommands; /**< whether to ignore all TraCI commands that only make sense when the server has a graphical user interface */
TraCIRegionOfInterest roi; /**< Can return whether a given position lies within the simulation's region of interest. Modules are destroyed and re-created as managed vehicles leave and re-enter the ROI */
double areaSum;
AnnotationManager* annotations;
std::unique_ptr<TraCIConnection> connection;
std::unique_ptr<TraCICommandInterface> commandIfc;
size_t nextNodeVectorIndex; /**< next OMNeT++ module vector index to use */
std::map<std::string, cModule*> hosts; /**< vector of all hosts managed by us */
std::set<std::string> unEquippedHosts;
std::set<std::string> subscribedVehicles; /**< all vehicles we have already subscribed to */
std::map<std::string, cModule*> trafficLights; /**< vector of all traffic lights managed by us */
uint32_t activeVehicleCount; /**< number of vehicles, be it parking or driving **/
uint32_t parkingVehicleCount; /**< number of parking vehicles, derived from parking start/end events */
uint32_t drivingVehicleCount; /**< number of driving, as reported by sumo */
bool autoShutdownTriggered;
cMessage* connectAndStartTrigger; /**< self-message scheduled for when to connect to TraCI server and start running */
cMessage* executeOneTimestepTrigger; /**< self-message scheduled for when to next call executeOneTimestep */
BaseWorldUtility* world;
std::map<const BaseMobility*, const MobileHostObstacle*> vehicleObstacles;
VehicleObstacleControl* vehicleObstacleControl;
void executeOneTimestep(); /**< read and execute all commands for the next timestep */
virtual void init_traci();
virtual void preInitializeModule(cModule* mod, const std::string& nodeId, const Coord& position, const std::string& road_id, double speed, Heading heading, VehicleSignalSet signals);
virtual void updateModulePosition(cModule* mod, const Coord& p, const std::string& edge, double speed, Heading heading, VehicleSignalSet signals);
void addModule(std::string nodeId, std::string type, std::string name, std::string displayString, const Coord& position, std::string road_id = "", double speed = -1, Heading heading = Heading::nan, VehicleSignalSet signals = {VehicleSignal::undefined}, double length = 0, double height = 0, double width = 0);
cModule* getManagedModule(std::string nodeId); /**< returns a pointer to the managed module named moduleName, or 0 if no module can be found */
void deleteManagedModule(std::string nodeId);
bool isModuleUnequipped(std::string nodeId); /**< returns true if this vehicle is Unequipped */
void subscribeToVehicleVariables(std::string vehicleId);
void unsubscribeFromVehicleVariables(std::string vehicleId);
void processSimSubscription(std::string objectId, TraCIBuffer& buf);
void processVehicleSubscription(std::string objectId, TraCIBuffer& buf);
void processSubcriptionResult(TraCIBuffer& buf);
void subscribeToTrafficLightVariables(std::string tlId);
void unsubscribeFromTrafficLightVariables(std::string tlId);
void processTrafficLightSubscription(std::string objectId, TraCIBuffer& buf);
/**
* parses the vector of module types in ini file
*
* in case of inconsistencies the function kills the simulation
*/
void parseModuleTypes();
/**
* transforms a list of mappings of an omnetpp.ini parameter in a list
*/
TypeMapping parseMappings(std::string parameter, std::string parameterName, bool allowEmpty = false);
virtual int getPortNumber() const;
};
class VEINS_API TraCIScenarioManagerAccess {
public:
TraCIScenarioManager* get()
{
return FindModule<TraCIScenarioManager*>::findGlobalModule();
};
};
} // namespace veins
| 9,225 | 42.933333 | 313 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerForker.cc | //
// Copyright (C) 2006-2016 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#define WANT_WINSOCK2
#include <platdep/sockets.h>
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__) || defined(_WIN64)
#include <ws2tcpip.h>
#else
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
#include <sstream>
#include <iostream>
#include <fstream>
#include "veins/modules/mobility/traci/TraCIScenarioManagerForker.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include "veins/modules/mobility/traci/TraCILauncher.h"
using veins::TraCILauncher;
using veins::TraCIScenarioManagerForker;
Define_Module(veins::TraCIScenarioManagerForker);
namespace {
template <typename T>
inline std::string replace(std::string haystack, std::string needle, T newValue)
{
size_t i = haystack.find(needle, 0);
if (i == std::string::npos) return haystack;
std::ostringstream os;
os << newValue;
haystack.replace(i, needle.length(), os.str());
return haystack;
}
} // namespace
TraCIScenarioManagerForker::TraCIScenarioManagerForker()
{
server = nullptr;
}
TraCIScenarioManagerForker::~TraCIScenarioManagerForker()
{
killServer();
}
void TraCIScenarioManagerForker::initialize(int stage)
{
if (stage == 1) {
commandLine = par("commandLine").stringValue();
command = par("command").stringValue();
configFile = par("configFile").stringValue();
seed = par("seed");
killServer();
}
TraCIScenarioManager::initialize(stage);
if (stage == 1) {
startServer();
}
}
void TraCIScenarioManagerForker::finish()
{
TraCIScenarioManager::finish();
killServer();
}
void TraCIScenarioManagerForker::startServer()
{
// autoset seed, if requested
if (seed == -1) {
const char* seed_s = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNNUMBER);
seed = atoi(seed_s);
}
// assemble commandLine
commandLine = replace(commandLine, "$command", command);
commandLine = replace(commandLine, "$configFile", configFile);
commandLine = replace(commandLine, "$seed", seed);
commandLine = replace(commandLine, "$port", port);
server = new TraCILauncher(commandLine);
}
void TraCIScenarioManagerForker::killServer()
{
if (server) {
delete server;
server = nullptr;
}
}
int TraCIScenarioManagerForker::getPortNumber() const
{
int port = TraCIScenarioManager::getPortNumber();
if (port != -1) {
return port;
}
// find a free port for the forker if port is still -1
if (initsocketlibonce() != 0) throw cRuntimeError("Could not init socketlib");
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
throw cRuntimeError("Failed to create socket: %s", strerror(errno));
}
struct sockaddr_in serv_addr;
struct sockaddr* serv_addr_p = (struct sockaddr*) &serv_addr;
memset(serv_addr_p, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = 0;
if (::bind(sock, serv_addr_p, sizeof(serv_addr)) < 0) {
throw cRuntimeError("Failed to bind socket: %s", strerror(errno));
}
socklen_t len = sizeof(serv_addr);
if (getsockname(sock, serv_addr_p, &len) < 0) {
throw cRuntimeError("Failed to get hostname: %s", strerror(errno));
}
port = ntohs(serv_addr.sin_port);
closesocket(sock);
return port;
}
| 4,425 | 27.554839 | 122 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerForker.h | //
// Copyright (C) 2006-2016 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/modules/mobility/traci/TraCILauncher.h"
namespace veins {
/**
* @brief
*
* Extends the TraCIScenarioManager to automatically fork an instance of SUMO when needed.
*
* All other functionality is provided by the TraCIScenarioManager.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer, Florian Hagenauer
*
* @see TraCIMobility
* @see TraCIScenarioManager
*
*/
class VEINS_API TraCIScenarioManagerForker : public TraCIScenarioManager {
public:
TraCIScenarioManagerForker();
~TraCIScenarioManagerForker() override;
void initialize(int stage) override;
void finish() override;
protected:
std::string commandLine; /**< command line for running TraCI server (substituting $configFile, $seed, $port) */
std::string command; /**< substitution for $command parameter */
std::string configFile; /**< substitution for $configFile parameter */
int seed; /**< substitution for $seed parameter (-1: current run number) */
TraCILauncher* server;
virtual void startServer();
virtual void killServer();
int getPortNumber() const override;
};
class VEINS_API TraCIScenarioManagerForkerAccess {
public:
TraCIScenarioManagerForker* get()
{
return FindModule<TraCIScenarioManagerForker*>::findGlobalModule();
};
};
} // namespace veins
| 2,427 | 31.373333 | 115 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.cc | //
// Copyright (C) 2006-2012 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIConstants.h"
#include <sstream>
#include <iostream>
#include <fstream>
namespace veins {
namespace TraCIConstants {
const uint8_t CMD_FILE_SEND = 0x75;
} // namespace TraCIConstants
} // namespace veins
using namespace veins::TraCIConstants;
using veins::TraCIScenarioManagerLaunchd;
Define_Module(veins::TraCIScenarioManagerLaunchd);
TraCIScenarioManagerLaunchd::~TraCIScenarioManagerLaunchd()
{
}
void TraCIScenarioManagerLaunchd::initialize(int stage)
{
if (stage != 1) {
TraCIScenarioManager::initialize(stage);
return;
}
launchConfig = par("launchConfig").xmlValue();
seed = par("seed");
cXMLElementList basedir_nodes = launchConfig->getElementsByTagName("basedir");
if (basedir_nodes.size() == 0) {
// default basedir is where current network file was loaded from
std::string basedir = cSimulation::getActiveSimulation()->getEnvir()->getConfig()->getConfigEntry("network").getBaseDirectory();
cXMLElement* basedir_node = new cXMLElement("basedir", __FILE__, launchConfig);
basedir_node->setAttribute("path", basedir.c_str());
launchConfig->appendChild(basedir_node);
}
cXMLElementList seed_nodes = launchConfig->getElementsByTagName("seed");
if (seed_nodes.size() == 0) {
if (seed == -1) {
// default seed is current repetition
const char* seed_s = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNNUMBER);
seed = atoi(seed_s);
}
std::stringstream ss;
ss << seed;
cXMLElement* seed_node = new cXMLElement("seed", __FILE__, launchConfig);
seed_node->setAttribute("value", ss.str().c_str());
launchConfig->appendChild(seed_node);
}
TraCIScenarioManager::initialize(stage);
}
void TraCIScenarioManagerLaunchd::finish()
{
TraCIScenarioManager::finish();
}
void TraCIScenarioManagerLaunchd::init_traci()
{
{
std::pair<uint32_t, std::string> version = getCommandInterface()->getVersion();
uint32_t apiVersion = version.first;
std::string serverVersion = version.second;
if (apiVersion == 1) {
EV_DEBUG << "TraCI server \"" << serverVersion << "\" reports API version " << apiVersion << endl;
}
else {
throw cRuntimeError("TraCI server \"%s\" reports API version %d, which is unsupported. We recommend using the version of sumo-launchd that ships with Veins.", serverVersion.c_str(), apiVersion);
}
}
#if OMNETPP_VERSION <= 0x500
std::string contents = launchConfig->tostr(0);
#else
std::string contents = launchConfig->getXML();
#endif
TraCIBuffer buf;
buf << std::string("sumo-launchd.launch.xml") << contents;
connection->sendMessage(makeTraCICommand(CMD_FILE_SEND, buf));
TraCIBuffer obuf(connection->receiveMessage());
uint8_t cmdLength;
obuf >> cmdLength;
uint8_t commandResp;
obuf >> commandResp;
if (commandResp != CMD_FILE_SEND) throw cRuntimeError("Expected response to command %d, but got one for command %d", CMD_FILE_SEND, commandResp);
uint8_t result;
obuf >> result;
std::string description;
obuf >> description;
if (result != RTYPE_OK) {
EV << "Warning: Received non-OK response from TraCI server to command " << CMD_FILE_SEND << ":" << description.c_str() << std::endl;
}
TraCIScenarioManager::init_traci();
}
| 4,535 | 34.162791 | 206 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.h | //
// Copyright (C) 2006-2012 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
namespace veins {
/**
* @brief
* Extends the TraCIScenarioManager for use with sumo-launchd.py and SUMO.
*
* Connects to a running instance of the sumo-launchd.py script
* to automatically launch/kill SUMO when the simulation starts/ends.
*
* All other functionality is provided by the TraCIScenarioManager.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer, David Eckhoff
*
* @see TraCIMobility
* @see TraCIScenarioManager
*
*/
class VEINS_API TraCIScenarioManagerLaunchd : public TraCIScenarioManager {
public:
~TraCIScenarioManagerLaunchd() override;
void initialize(int stage) override;
void finish() override;
protected:
cXMLElement* launchConfig; /**< launch configuration to send to sumo-launchd */
int seed; /**< seed value to set in launch configuration, if missing (-1: current run number) */
void init_traci() override;
};
class VEINS_API TraCIScenarioManagerLaunchdAccess {
public:
TraCIScenarioManagerLaunchd* get()
{
return FindModule<TraCIScenarioManagerLaunchd*>::findGlobalModule();
};
};
} // namespace veins
| 2,203 | 30.485714 | 113 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScreenRecorder.cc | //
// Copyright (C) 2006-2014 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCIScreenRecorder.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#ifdef _WIN32
#define realpath(N, R) _fullpath((R), (N), _MAX_PATH)
#endif /* _WIN32 */
using veins::TraCIScreenRecorder;
Define_Module(veins::TraCIScreenRecorder);
void TraCIScreenRecorder::initialize(int stage)
{
if (stage == 0) {
takeScreenshot = new cMessage("take screenshot");
takeScreenshot->setSchedulingPriority(1); // this schedules screenshots after TraCI timesteps
scheduleAt(par("start"), takeScreenshot);
return;
}
}
void TraCIScreenRecorder::handleMessage(cMessage* msg)
{
ASSERT(msg == takeScreenshot);
// get dirname
const char* dirname = par("dirname").stringValue();
if (std::string(dirname) == "") {
dirname = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RESULTDIR);
}
// get absolute path of dirname (the TraCI server might be running in a different directory than OMNeT++)
std::string dirname_abs;
{
char* s = realpath(dirname, nullptr);
if (!s) {
perror("cannot open output directory");
throw cRuntimeError("cannot open output directory '%s'", dirname);
}
dirname_abs = s;
free(s);
}
// get filename template
std::string filenameTemplate = par("filenameTemplate").stdstringValue();
if (filenameTemplate == "") {
const char* myRunID = cSimulation::getActiveSimulation()->getEnvir()->getConfigEx()->getVariable(CFGVAR_RUNID);
filenameTemplate = "screenshot-" + std::string(myRunID) + "-@%08.2f.png";
#ifdef _WIN32
// replace ':' with '-'
for (std::string::iterator i = filenameTemplate.begin(); i != filenameTemplate.end(); ++i)
if (*i == ':') *i = '-';
#endif /* _WIN32 */
}
// assemble filename
std::string filename;
{
std::string tmpl = dirname_abs + "/" + filenameTemplate;
char buf[1024];
snprintf(buf, 1024, tmpl.c_str(), simTime().dbl());
buf[1023] = 0;
filename = buf;
}
// take screenshot
TraCIScenarioManager* manager = TraCIScenarioManagerAccess().get();
ASSERT(manager);
TraCICommandInterface* traci = manager->getCommandInterface();
if (!traci) {
throw cRuntimeError("Cannot create screenshot: TraCI is not connected yet");
}
TraCICommandInterface::GuiView view = traci->guiView(par("viewName"));
view.takeScreenshot(filename);
// schedule next screenshot
simtime_t stop = par("stop");
if ((stop == -1) || (simTime() < stop)) {
scheduleAt(simTime() + par("interval"), takeScreenshot);
}
}
void TraCIScreenRecorder::finish()
{
cancelAndDelete(takeScreenshot);
}
| 3,770 | 33.281818 | 119 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIScreenRecorder.h | //
// Copyright (C) 2006-2014 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
namespace veins {
/**
* @brief
* Simple support module to take (a series of) screenshots of a simulation running in the TraCI server.
*
* Note that the TraCI server needs to be run in GUI mode and support taking screenshots for this to work.
*
* The screenshots can then be converted to a video using something along the lines of
* mencoder 'mf://results/screenshot-*.png' -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer
*
* @see TraCIScenarioManager
*
*/
class VEINS_API TraCIScreenRecorder : public cSimpleModule {
public:
void initialize(int stage) override;
void handleMessage(cMessage* msg) override;
void finish() override;
protected:
cMessage* takeScreenshot;
};
} // namespace veins
| 1,867 | 32.357143 | 144 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIVehicleInserter.cc | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "veins/modules/mobility/traci/TraCIVehicleInserter.h"
#include <vector>
#include <algorithm>
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
#include "veins/modules/mobility/traci/TraCIMobility.h"
#include "veins/base/utils/FindModule.h"
Define_Module(veins::TraCIVehicleInserter);
using namespace veins;
TraCIVehicleInserter::TraCIVehicleInserter()
: mobRng(nullptr)
{
}
TraCIVehicleInserter::~TraCIVehicleInserter()
{
}
int TraCIVehicleInserter::numInitStages() const
{
return std::max(cSimpleModule::numInitStages(), 2);
}
void TraCIVehicleInserter::initialize(int stage)
{
cSimpleModule::initialize(stage);
if (stage != 1) {
return;
}
// internal 1
manager = TraCIScenarioManagerAccess().get();
// signals
manager->subscribe(TraCIScenarioManager::traciModuleAddedSignal, this);
manager->subscribe(TraCIScenarioManager::traciTimestepBeginSignal, this);
// parameters
vehicleRngIndex = par("vehicleRngIndex");
numVehicles = par("numVehicles");
// internal 2
vehicleNameCounter = 0;
mobRng = getRNG(vehicleRngIndex);
}
void TraCIVehicleInserter::finish()
{
unsubscribe(TraCIScenarioManager::traciModuleAddedSignal, this);
unsubscribe(TraCIScenarioManager::traciTimestepBeginSignal, this);
}
void TraCIVehicleInserter::finish(cComponent* component, simsignal_t signalID)
{
cListener::finish(component, signalID);
}
void TraCIVehicleInserter::handleMessage(cMessage* msg)
{
}
void TraCIVehicleInserter::receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details)
{
if (signalID == TraCIScenarioManager::traciModuleAddedSignal) {
ASSERT(manager->isConnected());
cModule* mod = check_and_cast<cModule*>(obj);
auto* mob = FindModule<TraCIMobility*>::findSubModule(mod);
ASSERT(mob != nullptr);
std::string nodeId = mob->getExternalId();
if (queuedVehicles.find(nodeId) != queuedVehicles.end()) {
queuedVehicles.erase(nodeId);
}
}
}
void TraCIVehicleInserter::receiveSignal(cComponent* source, simsignal_t signalID, const SimTime& t, cObject* details)
{
if (signalID == TraCIScenarioManager::traciTimestepBeginSignal) {
ASSERT(manager->isConnected());
if (simTime() > 1) {
if (vehicleTypeIds.size() == 0) {
std::list<std::string> vehTypes = manager->getCommandInterface()->getVehicleTypeIds();
for (std::list<std::string>::const_iterator i = vehTypes.begin(); i != vehTypes.end(); ++i) {
if (i->substr(0, 8).compare("DEFAULT_") != 0) {
EV_DEBUG << *i << std::endl;
vehicleTypeIds.push_back(*i);
}
}
}
if (routeIds.size() == 0) {
std::list<std::string> routes = manager->getCommandInterface()->getRouteIds();
for (std::list<std::string>::const_iterator i = routes.begin(); i != routes.end(); ++i) {
std::string routeId = *i;
if (par("useRouteDistributions").boolValue() == true) {
if (std::count(routeId.begin(), routeId.end(), '#') >= 1) {
EV_DEBUG << "Omitting route " << routeId << " as it seems to be a member of a route distribution (found '#' in name)" << std::endl;
continue;
}
}
EV_DEBUG << "Adding " << routeId << " to list of possible routes" << std::endl;
routeIds.push_back(routeId);
}
}
for (int i = manager->getManagedHosts().size() + queuedVehicles.size(); i < numVehicles; i++) {
insertNewVehicle();
}
}
insertVehicles();
}
}
void TraCIVehicleInserter::insertNewVehicle()
{
std::string type;
if (vehicleTypeIds.size()) {
int vehTypeId = mobRng->intRand(vehicleTypeIds.size());
type = vehicleTypeIds[vehTypeId];
}
else {
type = "DEFAULT_VEHTYPE";
}
int routeId = mobRng->intRand(routeIds.size());
vehicleInsertQueue[routeId].push(type);
}
void TraCIVehicleInserter::insertVehicles()
{
for (std::map<int, std::queue<std::string>>::iterator i = vehicleInsertQueue.begin(); i != vehicleInsertQueue.end();) {
std::string route = routeIds[i->first];
EV_DEBUG << "process " << route << std::endl;
std::queue<std::string> vehicles = i->second;
while (!i->second.empty()) {
bool suc = false;
std::string type = i->second.front();
std::stringstream veh;
veh << type << "_" << vehicleNameCounter;
EV_DEBUG << "trying to add " << veh.str() << " with " << route << " vehicle type " << type << std::endl;
suc = manager->getCommandInterface()->addVehicle(veh.str(), type, route, simTime());
if (!suc) {
i->second.pop();
}
else {
EV_DEBUG << "successful inserted " << veh.str() << std::endl;
queuedVehicles.insert(veh.str());
i->second.pop();
vehicleNameCounter++;
}
}
std::map<int, std::queue<std::string>>::iterator tmp = i;
++tmp;
vehicleInsertQueue.erase(i);
i = tmp;
}
}
| 6,422 | 33.532258 | 159 | cc |
null | AICP-main/veins/src/veins/modules/mobility/traci/TraCIVehicleInserter.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <queue>
#include "veins/veins.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
namespace veins {
/**
* @brief
* Uses the TraCIScenarioManager to programmatically insert new vehicles at the TraCI server.
*
* This is done whenever the total number of active vehicles drops below a given number.
*
* See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
*
* @author Christoph Sommer, David Eckhoff, Falko Dressler, Zheng Yao, Tobias Mayer, Alvaro Torres Cortes, Luca Bedogni
*
* @see TraCIScenarioManager
*
*/
class VEINS_API TraCIVehicleInserter : public cSimpleModule, public cListener {
public:
TraCIVehicleInserter();
~TraCIVehicleInserter() override;
int numInitStages() const override;
void initialize(int stage) override;
void finish() override;
void finish(cComponent* component, simsignal_t signalID) override;
void handleMessage(cMessage* msg) override;
void receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details) override;
void receiveSignal(cComponent* source, simsignal_t signalID, const SimTime& t, cObject* details) override;
protected:
/**
* adds a new vehicle to the queue which are tried to be inserted at the next SUMO time step;
*/
void insertNewVehicle();
/**
* tries to add all vehicles in the vehicle queue to SUMO;
*/
void insertVehicles();
// parameters
int vehicleRngIndex;
int numVehicles;
// internal
TraCIScenarioManager* manager;
cRNG* mobRng;
std::map<int, std::queue<std::string>> vehicleInsertQueue;
std::set<std::string> queuedVehicles;
std::vector<std::string> routeIds;
uint32_t vehicleNameCounter;
std::vector<std::string> vehicleTypeIds;
};
} // namespace veins
| 2,768 | 32.361446 | 119 | h |
null | AICP-main/veins/src/veins/modules/mobility/traci/VehicleSignal.h | //
// Copyright (C) 2018 Dominik S. Buse <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include "veins/veins.h"
#include "veins/base/utils/EnumBitset.h"
namespace veins {
enum class VehicleSignal : uint32_t {
blinker_right,
blinker_left,
blinker_emergency,
brakelight,
frontlight,
foglight,
highbeam,
backdrive,
wiper,
door_open_left,
door_open_right,
emergency_blue,
emergency_red,
emergency_yellow,
undefined
};
template <>
struct VEINS_API EnumTraits<VehicleSignal> {
static const VehicleSignal max = VehicleSignal::undefined;
};
using VehicleSignalSet = EnumBitset<VehicleSignal>;
} // namespace veins
| 1,500 | 25.333333 | 76 | h |
null | AICP-main/veins/src/veins/modules/obstacle/MobileHostObstacle.cc | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <set>
#include <limits>
#include "veins/modules/obstacle/MobileHostObstacle.h"
#include "veins/base/modules/BaseMobility.h"
#include "veins/base/utils/Heading.h"
using veins::Coord;
using veins::MobileHostObstacle;
namespace {
bool isPointInObstacle(Coord point, const MobileHostObstacle::Coords& shape)
{
bool isInside = false;
auto i = shape.begin();
auto j = (shape.rbegin() + 1).base();
for (; i != shape.end(); j = i++) {
bool inYRangeUp = (point.y >= i->y) && (point.y < j->y);
bool inYRangeDown = (point.y >= j->y) && (point.y < i->y);
bool inYRange = inYRangeUp || inYRangeDown;
if (!inYRange) continue;
bool intersects = point.x < (i->x + ((point.y - i->y) * (j->x - i->x) / (j->y - i->y)));
if (!intersects) continue;
isInside = !isInside;
}
return isInside;
}
double segmentsIntersectAt(Coord p1From, Coord p1To, Coord p2From, Coord p2To)
{
Coord p1Vec = p1To - p1From;
Coord p2Vec = p2To - p2From;
Coord p1p2 = p1From - p2From;
double D = (p1Vec.x * p2Vec.y - p1Vec.y * p2Vec.x);
double p1Frac = (p2Vec.x * p1p2.y - p2Vec.y * p1p2.x) / D;
if (p1Frac < 0 || p1Frac > 1) return -1;
double p2Frac = (p1Vec.x * p1p2.y - p1Vec.y * p1p2.x) / D;
if (p2Frac < 0 || p2Frac > 1) return -1;
return p1Frac;
}
} // namespace
MobileHostObstacle::Coords MobileHostObstacle::getShape(simtime_t t) const
{
double l = getLength();
double o = getHostPositionOffset(); // this is the shift we have to undo in order to (given the OMNeT++ host position) get the car's front bumper position
double w = getWidth() / 2;
const BaseMobility* m = getMobility();
Coord p = m->getPositionAt(t);
double a = Heading::fromCoord(m->getCurrentOrientation()).getRad();
Coords shape;
shape.push_back(p + Coord(-(l - o), -w).rotatedYaw(-a));
shape.push_back(p + Coord(+o, -w).rotatedYaw(-a));
shape.push_back(p + Coord(+o, +w).rotatedYaw(-a));
shape.push_back(p + Coord(-(l - o), +w).rotatedYaw(-a));
return shape;
}
bool MobileHostObstacle::maybeInBounds(double x1, double y1, double x2, double y2, simtime_t t) const
{
double l = getLength();
double o = getHostPositionOffset(); // this is the shift we have to undo in order to (given the OMNeT++ host position) get the car's front bumper position
double w = getWidth() / 2;
const BaseMobility* m = getMobility();
Coord p = m->getPositionAt(t);
double lw = std::max(l, w);
double xx1 = p.x - std::abs(o) - lw;
double xx2 = p.x + std::abs(o) + lw;
double yy1 = p.y - std::abs(o) - lw;
double yy2 = p.y + std::abs(o) + lw;
if (xx2 < x1) return false;
if (xx1 > x2) return false;
if (yy2 < y1) return false;
if (yy1 > y2) return false;
return true;
}
double MobileHostObstacle::getIntersectionPoint(const Coord& senderPos, const Coord& receiverPos, simtime_t t) const
{
const double not_a_number = std::numeric_limits<double>::quiet_NaN();
MobileHostObstacle::Coords shape = getShape(t);
// shortcut if sender is inside
bool senderInside = isPointInObstacle(senderPos, shape);
if (senderInside) return 0;
// get a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with this obstacle
std::multiset<double> intersectAt;
bool doesIntersect = false;
MobileHostObstacle::Coords::const_iterator i = shape.begin();
MobileHostObstacle::Coords::const_iterator j = (shape.rbegin() + 1).base();
for (; i != shape.end(); j = i++) {
Coord c1 = *i;
Coord c2 = *j;
double inter = segmentsIntersectAt(senderPos, receiverPos, c1, c2);
if (inter != -1) {
doesIntersect = true;
EV << "intersect: " << inter << endl;
intersectAt.insert(inter);
}
}
// shortcut if no intersections
if (!doesIntersect) {
bool receiverInside = isPointInObstacle(receiverPos, shape);
if (receiverInside) return senderPos.distance(receiverPos);
return not_a_number;
}
return (*intersectAt.begin() * senderPos.distance(receiverPos));
}
| 5,088 | 33.619048 | 158 | cc |
null | AICP-main/veins/src/veins/modules/obstacle/MobileHostObstacle.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <vector>
#include "veins/base/utils/Coord.h"
#include "veins/base/utils/AntennaPosition.h"
namespace veins {
class BaseMobility;
/**
* Obstacle for radio waves derived from a mobile host's body.
*
* Primarily used for VehicleObstacleShadowing.
*/
class VEINS_API MobileHostObstacle {
public:
using Coords = std::vector<Coord>;
MobileHostObstacle(std::vector<AntennaPosition> initialAntennaPositions, BaseMobility* mobility, double length, double hostPositionOffset, double width, double height)
: initialAntennaPositions(std::move(initialAntennaPositions))
, mobility(mobility)
, length(length)
, hostPositionOffset(hostPositionOffset)
, width(width)
, height(height)
{
}
void setMobility(BaseMobility* mobility)
{
this->mobility = mobility;
}
void setLength(double d)
{
this->length = d;
}
void setHostPositionOffset(double d)
{
this->hostPositionOffset = d;
}
void setWidth(double d)
{
this->width = d;
}
void setHeight(double d)
{
this->height = d;
}
const std::vector<AntennaPosition>& getInitialAntennaPositions() const
{
return initialAntennaPositions;
}
const BaseMobility* getMobility() const
{
return mobility;
}
double getLength() const
{
return length;
}
double getHostPositionOffset() const
{
return hostPositionOffset;
}
double getWidth() const
{
return width;
}
double getHeight() const
{
return height;
}
Coords getShape(simtime_t t) const;
bool maybeInBounds(double x1, double y1, double x2, double y2, simtime_t t) const;
/**
* return closest point (in meters) along (senderPos--receiverPos) where this obstacle overlaps, or NAN if it doesn't
*/
double getIntersectionPoint(const Coord& senderPos, const Coord& receiverPos, simtime_t t) const;
protected:
/**
* Positions with identiers for all antennas connected to the host of this obstacle.
*
* Used to identify which host this obstacle belongs to.
* Even works after the host has been destroyed (as AntennaPosition only stores the comonnent id).
*/
std::vector<AntennaPosition> initialAntennaPositions;
BaseMobility* mobility;
double length;
double hostPositionOffset;
double width;
double height;
};
} // namespace veins
| 3,398 | 26.634146 | 171 | h |
null | AICP-main/veins/src/veins/modules/obstacle/Obstacle.cc | //
// Copyright (C) 2010-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <algorithm>
#include "veins/modules/obstacle/Obstacle.h"
using namespace veins;
using veins::Obstacle;
Obstacle::Obstacle(std::string id, std::string type, double attenuationPerCut, double attenuationPerMeter)
: visualRepresentation(nullptr)
, id(id)
, type(type)
, attenuationPerCut(attenuationPerCut)
, attenuationPerMeter(attenuationPerMeter)
{
}
void Obstacle::setShape(Coords shape)
{
coords = shape;
bboxP1 = Coord(1e7, 1e7);
bboxP2 = Coord(-1e7, -1e7);
for (Coords::const_iterator i = coords.begin(); i != coords.end(); ++i) {
bboxP1.x = std::min(i->x, bboxP1.x);
bboxP1.y = std::min(i->y, bboxP1.y);
bboxP2.x = std::max(i->x, bboxP2.x);
bboxP2.y = std::max(i->y, bboxP2.y);
}
}
const Obstacle::Coords& Obstacle::getShape() const
{
return coords;
}
const Coord Obstacle::getBboxP1() const
{
return bboxP1;
}
const Coord Obstacle::getBboxP2() const
{
return bboxP2;
}
bool Obstacle::containsPoint(Coord point) const
{
bool isInside = false;
const Obstacle::Coords& shape = getShape();
Obstacle::Coords::const_iterator i = shape.begin();
Obstacle::Coords::const_iterator j = (shape.rbegin() + 1).base();
for (; i != shape.end(); j = i++) {
bool inYRangeUp = (point.y >= i->y) && (point.y < j->y);
bool inYRangeDown = (point.y >= j->y) && (point.y < i->y);
bool inYRange = inYRangeUp || inYRangeDown;
if (!inYRange) continue;
bool intersects = point.x < (i->x + ((point.y - i->y) * (j->x - i->x) / (j->y - i->y)));
if (!intersects) continue;
isInside = !isInside;
}
return isInside;
}
namespace {
double segmentsIntersectAt(const Coord& p1From, const Coord& p1To, const Coord& p2From, const Coord& p2To)
{
double p1x = p1To.x - p1From.x;
double p1y = p1To.y - p1From.y;
double p2x = p2To.x - p2From.x;
double p2y = p2To.y - p2From.y;
double p1p2x = p1From.x - p2From.x;
double p1p2y = p1From.y - p2From.y;
double D = (p1x * p2y - p1y * p2x);
double p1Frac = (p2x * p1p2y - p2y * p1p2x) / D;
if (p1Frac < 0 || p1Frac > 1) return -1;
double p2Frac = (p1x * p1p2y - p1y * p1p2x) / D;
if (p2Frac < 0 || p2Frac > 1) return -1;
return p1Frac;
}
} // namespace
std::vector<double> Obstacle::getIntersections(const Coord& senderPos, const Coord& receiverPos) const
{
std::vector<double> intersectAt;
const Obstacle::Coords& shape = getShape();
Obstacle::Coords::const_iterator i = shape.begin();
Obstacle::Coords::const_iterator j = (shape.rbegin() + 1).base();
for (; i != shape.end(); j = i++) {
const Coord& c1 = *i;
const Coord& c2 = *j;
double i = segmentsIntersectAt(senderPos, receiverPos, c1, c2);
if (i != -1) {
intersectAt.push_back(i);
}
}
std::sort(intersectAt.begin(), intersectAt.end());
return intersectAt;
}
std::string Obstacle::getType() const
{
return type;
}
std::string Obstacle::getId() const
{
return id;
}
double Obstacle::getAttenuationPerCut() const
{
return attenuationPerCut;
}
double Obstacle::getAttenuationPerMeter() const
{
return attenuationPerMeter;
}
| 4,132 | 27.308219 | 106 | cc |
null | AICP-main/veins/src/veins/modules/obstacle/Obstacle.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <vector>
#include "veins/veins.h"
#include "veins/base/utils/Coord.h"
#include "veins/modules/world/annotations/AnnotationManager.h"
namespace veins {
/**
* stores information about an Obstacle for ObstacleControl
*/
class VEINS_API Obstacle {
public:
using Coords = std::vector<Coord>;
Obstacle(std::string id, std::string type, double attenuationPerCut, double attenuationPerMeter);
void setShape(Coords shape);
const Coords& getShape() const;
const Coord getBboxP1() const;
const Coord getBboxP2() const;
bool containsPoint(Coord Point) const;
std::string getType() const;
std::string getId() const;
double getAttenuationPerCut() const;
double getAttenuationPerMeter() const;
/**
* get a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with this obstacle
*/
std::vector<double> getIntersections(const Coord& senderPos, const Coord& receiverPos) const;
AnnotationManager::Annotation* visualRepresentation;
protected:
std::string id;
std::string type;
double attenuationPerCut; /**< in dB. attenuation per exterior border of obstacle */
double attenuationPerMeter; /**< in dB / m. to account for attenuation caused by interior of obstacle */
Coords coords;
Coord bboxP1;
Coord bboxP2;
};
} // namespace veins
| 2,293 | 30.861111 | 127 | h |
null | AICP-main/veins/src/veins/modules/obstacle/ObstacleControl.cc | //
// Copyright (C) 2010-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <sstream>
#include <map>
#include <set>
#include "veins/modules/obstacle/ObstacleControl.h"
#include "veins/base/modules/BaseWorldUtility.h"
using veins::ObstacleControl;
Define_Module(veins::ObstacleControl);
namespace {
veins::BBoxLookup rebuildBBoxLookup(const std::vector<std::unique_ptr<veins::Obstacle>>& obstacleOwner, int gridCellSize = 250)
{
std::vector<veins::Obstacle*> obstaclePointers;
obstaclePointers.reserve(obstacleOwner.size());
std::transform(obstacleOwner.begin(), obstacleOwner.end(), std::back_inserter(obstaclePointers), [](const std::unique_ptr<veins::Obstacle>& obstacle) { return obstacle.get(); });
auto playgroundSize = veins::FindModule<veins::BaseWorldUtility*>::findGlobalModule()->getPgs();
auto bboxFunction = [](veins::Obstacle* o) { return veins::BBoxLookup::Box{{o->getBboxP1().x, o->getBboxP1().y}, {o->getBboxP2().x, o->getBboxP2().y}}; };
return veins::BBoxLookup(obstaclePointers, bboxFunction, playgroundSize->x, playgroundSize->y, gridCellSize);
}
} // anonymous namespace
ObstacleControl::~ObstacleControl()
{
}
void ObstacleControl::initialize(int stage)
{
if (stage == 1) {
obstacleOwner.clear();
cacheEntries.clear();
isBboxLookupDirty = true;
annotations = AnnotationManagerAccess().getIfExists();
if (annotations) annotationGroup = annotations->createGroup("obstacles");
obstaclesXml = par("obstacles");
gridCellSize = par("gridCellSize");
if (gridCellSize < 1) {
throw cRuntimeError("gridCellSize was %d, but must be a positive integer number", gridCellSize);
}
addFromXml(obstaclesXml);
}
}
void ObstacleControl::finish()
{
obstacleOwner.clear();
}
void ObstacleControl::handleMessage(cMessage* msg)
{
if (msg->isSelfMessage()) {
handleSelfMsg(msg);
return;
}
throw cRuntimeError("ObstacleControl doesn't handle messages from other modules");
}
void ObstacleControl::handleSelfMsg(cMessage* msg)
{
throw cRuntimeError("ObstacleControl doesn't handle self-messages");
}
void ObstacleControl::addFromXml(cXMLElement* xml)
{
std::string rootTag = xml->getTagName();
if (rootTag != "obstacles") {
throw cRuntimeError("Obstacle definition root tag was \"%s\", but expected \"obstacles\"", rootTag.c_str());
}
cXMLElementList list = xml->getChildren();
for (cXMLElementList::const_iterator i = list.begin(); i != list.end(); ++i) {
cXMLElement* e = *i;
std::string tag = e->getTagName();
if (tag == "type") {
// <type id="building" db-per-cut="9" db-per-meter="0.4" />
ASSERT(e->getAttribute("id"));
std::string id = e->getAttribute("id");
ASSERT(e->getAttribute("db-per-cut"));
std::string perCutParS = e->getAttribute("db-per-cut");
double perCutPar = strtod(perCutParS.c_str(), nullptr);
ASSERT(e->getAttribute("db-per-meter"));
std::string perMeterParS = e->getAttribute("db-per-meter");
double perMeterPar = strtod(perMeterParS.c_str(), nullptr);
perCut[id] = perCutPar;
perMeter[id] = perMeterPar;
}
else if (tag == "poly") {
// <poly id="building#0" type="building" color="#F00" shape="16,0 8,13.8564 -8,13.8564 -16,0 -8,-13.8564 8,-13.8564" />
ASSERT(e->getAttribute("id"));
std::string id = e->getAttribute("id");
ASSERT(e->getAttribute("type"));
std::string type = e->getAttribute("type");
ASSERT(e->getAttribute("color"));
std::string color = e->getAttribute("color");
ASSERT(e->getAttribute("shape"));
std::string shape = e->getAttribute("shape");
Obstacle obs(id, type, getAttenuationPerCut(type), getAttenuationPerMeter(type));
std::vector<Coord> sh;
cStringTokenizer st(shape.c_str());
while (st.hasMoreTokens()) {
std::string xy = st.nextToken();
std::vector<double> xya = cStringTokenizer(xy.c_str(), ",").asDoubleVector();
ASSERT(xya.size() == 2);
sh.push_back(Coord(xya[0], xya[1]));
}
obs.setShape(sh);
add(obs);
}
else {
throw cRuntimeError("Found unknown tag in obstacle definition: \"%s\"", tag.c_str());
}
}
}
void ObstacleControl::addFromTypeAndShape(std::string id, std::string typeId, std::vector<Coord> shape)
{
if (!isTypeSupported(typeId)) {
throw cRuntimeError("Unsupported obstacle type: \"%s\"", typeId.c_str());
}
Obstacle obs(id, typeId, getAttenuationPerCut(typeId), getAttenuationPerMeter(typeId));
obs.setShape(shape);
add(obs);
}
void ObstacleControl::add(Obstacle obstacle)
{
Obstacle* o = new Obstacle(obstacle);
obstacleOwner.emplace_back(o);
// visualize using AnnotationManager
if (annotations) o->visualRepresentation = annotations->drawPolygon(o->getShape(), "red", annotationGroup);
cacheEntries.clear();
isBboxLookupDirty = true;
}
void ObstacleControl::erase(const Obstacle* obstacle)
{
if (annotations && obstacle->visualRepresentation) annotations->erase(obstacle->visualRepresentation);
for (auto itOwner = obstacleOwner.begin(); itOwner != obstacleOwner.end(); ++itOwner) {
// find owning pointer and remove it to deallocate obstacle
if (itOwner->get() == obstacle) {
obstacleOwner.erase(itOwner);
break;
}
}
cacheEntries.clear();
isBboxLookupDirty = true;
}
std::vector<std::pair<veins::Obstacle*, std::vector<double>>> ObstacleControl::getIntersections(const Coord& senderPos, const Coord& receiverPos) const
{
std::vector<std::pair<Obstacle*, std::vector<double>>> allIntersections;
// rebuild bounding box lookup structure if dirty (new obstacles added recently)
if (isBboxLookupDirty) {
bboxLookup = rebuildBBoxLookup(obstacleOwner);
isBboxLookupDirty = false;
}
auto candidateObstacles = bboxLookup.findOverlapping({senderPos.x, senderPos.y}, {receiverPos.x, receiverPos.y});
// remove duplicates
sort(candidateObstacles.begin(), candidateObstacles.end());
candidateObstacles.erase(unique(candidateObstacles.begin(), candidateObstacles.end()), candidateObstacles.end());
for (Obstacle* o : candidateObstacles) {
// if obstacles has neither borders nor matter: bail.
if (o->getShape().size() < 2) continue;
auto foundIntersections = o->getIntersections(senderPos, receiverPos);
if (!foundIntersections.empty() || o->containsPoint(senderPos) || o->containsPoint(receiverPos)) {
allIntersections.emplace_back(o, foundIntersections);
}
}
return allIntersections;
}
double ObstacleControl::calculateAttenuation(const Coord& senderPos, const Coord& receiverPos) const
{
Enter_Method_Silent();
if ((perCut.size() == 0) || (perMeter.size() == 0)) {
throw cRuntimeError("Unable to use SimpleObstacleShadowing: No obstacle types have been configured");
}
if (obstacleOwner.size() == 0) {
throw cRuntimeError("Unable to use SimpleObstacleShadowing: No obstacles have been added");
}
// return cached result, if available
CacheKey cacheKey(senderPos, receiverPos);
CacheEntries::const_iterator cacheEntryIter = cacheEntries.find(cacheKey);
if (cacheEntryIter != cacheEntries.end()) {
return cacheEntryIter->second;
}
// get intersections
auto intersections = getIntersections(senderPos, receiverPos);
double factor = 1;
for (auto i = intersections.begin(); i != intersections.end(); ++i) {
auto o = i->first;
auto intersectAt = i->second;
// if beam interacts with neither borders nor matter: bail.
bool senderInside = o->containsPoint(senderPos);
bool receiverInside = o->containsPoint(receiverPos);
if ((intersectAt.size() == 0) && !senderInside && !receiverInside) continue;
// remember number of cuts before messing with intersection points
double numCuts = intersectAt.size();
// for distance calculation, make sure every other pair of points marks transition through matter and void, respectively.
if (senderInside) intersectAt.insert(intersectAt.begin(), 0);
if (receiverInside) intersectAt.push_back(1);
ASSERT((intersectAt.size() % 2) == 0);
// sum up distances in matter.
double fractionInObstacle = 0;
for (auto i = intersectAt.begin(); i != intersectAt.end();) {
double p1 = *(i++);
double p2 = *(i++);
fractionInObstacle += (p2 - p1);
}
// calculate attenuation
double totalDistance = senderPos.distance(receiverPos);
double attenuation = (o->getAttenuationPerCut() * numCuts) + (o->getAttenuationPerMeter() * fractionInObstacle * totalDistance);
factor *= pow(10.0, -attenuation / 10.0);
// bail if attenuation is already extremely high
if (factor < 1e-30) break;
}
// cache result
if (cacheEntries.size() >= 1000) cacheEntries.clear();
cacheEntries[cacheKey] = factor;
return factor;
}
double ObstacleControl::getAttenuationPerCut(std::string type)
{
if (perCut.find(type) != perCut.end())
return perCut[type];
else {
throw cRuntimeError("Obstacle type %s unknown", type.c_str());
return -1;
}
}
double ObstacleControl::getAttenuationPerMeter(std::string type)
{
if (perMeter.find(type) != perMeter.end())
return perMeter[type];
else {
throw cRuntimeError("Obstacle type %s unknown", type.c_str());
return -1;
}
}
bool ObstacleControl::isTypeSupported(std::string type)
{
// the type of obstacle is supported if there are attenuation values for borders and interior
return (perCut.find(type) != perCut.end()) && (perMeter.find(type) != perMeter.end());
}
| 11,005 | 35.564784 | 182 | cc |
null | AICP-main/veins/src/veins/modules/obstacle/ObstacleControl.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <memory>
#include "veins/veins.h"
#include "veins/base/utils/Coord.h"
#include "veins/modules/obstacle/Obstacle.h"
#include "veins/modules/world/annotations/AnnotationManager.h"
#include "veins/modules/utility/BBoxLookup.h"
namespace veins {
/**
* ObstacleControl models obstacles that block radio transmissions.
*
* Each Obstacle is a polygon.
* Transmissions that cross one of the polygon's lines will have
* their receive power set to zero.
*/
class VEINS_API ObstacleControl : public cSimpleModule {
public:
~ObstacleControl() override;
void initialize(int stage) override;
int numInitStages() const override
{
return 2;
}
void finish() override;
void handleMessage(cMessage* msg) override;
void handleSelfMsg(cMessage* msg);
void addFromXml(cXMLElement* xml);
void addFromTypeAndShape(std::string id, std::string typeId, std::vector<Coord> shape);
void add(Obstacle obstacle);
void erase(const Obstacle* obstacle);
bool isTypeSupported(std::string type);
double getAttenuationPerCut(std::string type);
double getAttenuationPerMeter(std::string type);
/**
* get hit obstacles (along with a list of points (in [0, 1]) along the line between sender and receiver where the beam intersects with the respective obstacle) as well as any obstacle that contains the sender or receiver (with a list of potentially 0 points)
*/
std::vector<std::pair<Obstacle*, std::vector<double>>> getIntersections(const Coord& senderPos, const Coord& receiverPos) const;
/**
* calculate additional attenuation by obstacles, return multiplicative factor
*/
double calculateAttenuation(const Coord& senderPos, const Coord& receiverPos) const;
protected:
struct CacheKey {
const Coord senderPos;
const Coord receiverPos;
CacheKey(const Coord& senderPos, const Coord& receiverPos)
: senderPos(senderPos)
, receiverPos(receiverPos)
{
}
bool operator<(const CacheKey& o) const
{
if (senderPos.x < o.senderPos.x) return true;
if (senderPos.x > o.senderPos.x) return false;
if (senderPos.y < o.senderPos.y) return true;
if (senderPos.y > o.senderPos.y) return false;
if (receiverPos.x < o.receiverPos.x) return true;
if (receiverPos.x > o.receiverPos.x) return false;
if (receiverPos.y < o.receiverPos.y) return true;
if (receiverPos.y > o.receiverPos.y) return false;
return false;
}
};
typedef std::map<CacheKey, double> CacheEntries;
cXMLElement* obstaclesXml; /**< obstacles to add at startup */
int gridCellSize = 250; /**< size of square grid tiles for obstacle store */
std::vector<std::unique_ptr<Obstacle>> obstacleOwner;
AnnotationManager* annotations;
AnnotationManager::Group* annotationGroup;
std::map<std::string, double> perCut;
std::map<std::string, double> perMeter;
mutable CacheEntries cacheEntries;
mutable BBoxLookup bboxLookup;
mutable bool isBboxLookupDirty = true;
};
class VEINS_API ObstacleControlAccess {
public:
ObstacleControlAccess()
{
}
ObstacleControl* getIfExists()
{
return dynamic_cast<ObstacleControl*>(getSimulation()->getModuleByPath("obstacles"));
}
};
} // namespace veins
| 4,319 | 33.285714 | 263 | h |
null | AICP-main/veins/src/veins/modules/obstacle/VehicleObstacleControl.cc | //
// Copyright (C) 2010-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include <sstream>
#include <map>
#include <set>
#include <limits>
#include <cmath>
#include "veins/modules/obstacle/VehicleObstacleControl.h"
#include "veins/base/modules/BaseMobility.h"
#include "veins/base/connectionManager/ChannelAccess.h"
#include "veins/base/toolbox/Signal.h"
using veins::MobileHostObstacle;
using veins::Signal;
using veins::VehicleObstacleControl;
Define_Module(veins::VehicleObstacleControl);
VehicleObstacleControl::~VehicleObstacleControl() = default;
void VehicleObstacleControl::initialize(int stage)
{
if (stage == 1) {
annotations = AnnotationManagerAccess().getIfExists();
if (annotations) {
vehicleAnnotationGroup = annotations->createGroup("vehicleObstacles");
}
}
}
void VehicleObstacleControl::finish()
{
}
void VehicleObstacleControl::handleMessage(cMessage* msg)
{
if (msg->isSelfMessage()) {
handleSelfMsg(msg);
return;
}
throw cRuntimeError("VehicleObstacleControl doesn't handle messages from other modules");
}
void VehicleObstacleControl::handleSelfMsg(cMessage* msg)
{
throw cRuntimeError("VehicleObstacleControl doesn't handle self-messages");
}
const MobileHostObstacle* VehicleObstacleControl::add(MobileHostObstacle obstacle)
{
auto* o = new MobileHostObstacle(obstacle);
vehicleObstacles.push_back(o);
return o;
}
void VehicleObstacleControl::erase(const MobileHostObstacle* obstacle)
{
bool erasedOne = false;
for (auto k = vehicleObstacles.begin(); k != vehicleObstacles.end();) {
MobileHostObstacle* o = *k;
if (o == obstacle) {
erasedOne = true;
k = vehicleObstacles.erase(k);
}
else {
++k;
}
}
ASSERT(erasedOne);
delete obstacle;
}
Signal VehicleObstacleControl::getVehicleAttenuationSingle(double h1, double h2, double h, double d, double d1, Signal attenuationPrototype)
{
Signal attenuation = Signal(attenuationPrototype.getSpectrum());
for (uint16_t i = 0; i < attenuation.getNumValues(); i++) {
double freq = attenuation.getSpectrum().freqAt(i);
double lambda = BaseWorldUtility::speedOfLight() / freq;
double d2 = d - d1;
double y = (h2 - h1) / d * d1 + h1;
double H = h - y;
double r1 = sqrt(lambda * d1 * d2 / d);
double V0 = sqrt(2) * H / r1;
if (V0 <= -0.7) {
attenuation.at(i) = 0;
}
else {
attenuation.at(i) = 6.9 + 20 * log10(sqrt(pow((V0 - 0.1), 2) + 1) + V0 - 0.1);
}
}
return attenuation;
}
Signal VehicleObstacleControl::getVehicleAttenuationDZ(const std::vector<std::pair<double, double>>& dz_vec, Signal attenuationPrototype)
{
// basic sanity check
ASSERT(dz_vec.size() >= 2);
// make sure the list of x coordinates is sorted
for (size_t i = 0; i < dz_vec.size() - 1; i++) {
ASSERT(dz_vec[i].first < dz_vec[i + 1].first);
}
// find "major obstacles" (MOs) between sender and receiver via rope-stretching algorithm
/*
* |
* | |
* | : |
* | | : : | |
* mo0 mo1 mo2 mo3
* snd rcv
*/
std::vector<size_t> mo; ///< indices of MOs (this includes the sender and receiver)
mo.push_back(0);
for (size_t i = 0;;) {
double max_slope = -std::numeric_limits<double>::infinity();
size_t max_slope_index;
bool have_max_slope_index = false;
for (size_t j = i + 1; j < dz_vec.size(); ++j) {
double slope = (dz_vec[j].second - dz_vec[i].second) / (dz_vec[j].first - dz_vec[i].first);
if (slope > max_slope) {
max_slope = slope;
max_slope_index = j;
have_max_slope_index = true;
}
}
// Sanity check
ASSERT(have_max_slope_index);
if (max_slope_index >= dz_vec.size() - 1) break;
mo.push_back(max_slope_index);
i = max_slope_index;
}
mo.push_back(dz_vec.size() - 1);
// calculate attenuation due to MOs
Signal attenuation_mo(attenuationPrototype.getSpectrum());
for (size_t mm = 0; mm < mo.size() - 2; ++mm) {
size_t tx = mo[mm];
size_t ob = mo[mm + 1];
size_t rx = mo[mm + 2];
double h1 = dz_vec[tx].second;
double h2 = dz_vec[rx].second;
double d = dz_vec[rx].first - dz_vec[tx].first;
double d1 = dz_vec[ob].first - dz_vec[tx].first;
double h = dz_vec[ob].second;
Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype);
attenuation_mo += ad_mo;
}
// calculate attenuation due to "small obstacles" (i.e. the ones in-between MOs)
Signal attenuation_so(attenuationPrototype.getSpectrum());
for (size_t i = 0; i < mo.size() - 1; ++i) {
size_t delta = mo[i + 1] - mo[i];
if (delta == 1) {
// no obstacle in-between these two MOs
}
else if (delta == 2) {
// one obstacle in-between these two MOs
size_t tx = mo[i];
size_t ob = mo[i] + 1;
size_t rx = mo[i + 1];
double h1 = dz_vec[tx].second;
double h2 = dz_vec[rx].second;
double d = dz_vec[rx].first - dz_vec[tx].first;
double d1 = dz_vec[ob].first - dz_vec[tx].first;
double h = dz_vec[ob].second;
Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype);
attenuation_so += ad_mo;
}
else {
// multiple obstacles in-between these two MOs -- use the one closest to their line of sight
double x1 = dz_vec[mo[i]].first;
double y1 = dz_vec[mo[i]].second;
double x2 = dz_vec[mo[i + 1]].first;
double y2 = dz_vec[mo[i + 1]].second;
double min_delta_h = std::numeric_limits<float>::infinity();
size_t min_delta_h_index;
bool have_min_delta_h_index = false;
for (size_t j = mo[i] + 1; j < mo[i + 1]; ++j) {
double h = (y2 - y1) / (x2 - x1) * (dz_vec[j].first - x1) + y1;
double delta_h = h - dz_vec[j].second;
if (delta_h < min_delta_h) {
min_delta_h = delta_h;
min_delta_h_index = j;
have_min_delta_h_index = true;
}
}
// Sanity check
ASSERT(have_min_delta_h_index);
size_t tx = mo[i];
size_t ob = min_delta_h_index;
size_t rx = mo[i + 1];
double h1 = dz_vec[tx].second;
double h2 = dz_vec[rx].second;
double d = dz_vec[rx].first - dz_vec[tx].first;
double d1 = dz_vec[ob].first - dz_vec[tx].first;
double h = dz_vec[ob].second;
Signal ad_mo = getVehicleAttenuationSingle(h1, h2, h, d, d1, attenuationPrototype);
attenuation_so += ad_mo;
}
}
double c;
{
double prodS = 1;
double sumS = 0;
double prodSsum = 1;
double firstS = 0;
double lastS = 0;
double s_old = 0;
for (size_t jj = 0; jj < mo.size() - 1; ++jj) {
double s = dz_vec[mo[jj + 1]].first - dz_vec[mo[jj]].first; ///< distance between two MOs
prodS *= s;
sumS += s;
if (jj == 0)
firstS = s;
else if (jj > 0)
prodSsum *= (s + s_old);
if (jj == mo.size() - 2) lastS = s;
s_old = s;
}
c = -10 * log10((prodS * sumS) / (prodSsum * firstS * lastS));
}
return attenuation_mo + attenuation_so + c;
}
std::vector<std::pair<double, double>> VehicleObstacleControl::getPotentialObstacles(const AntennaPosition& senderPos_, const AntennaPosition& receiverPos_, const Signal& s) const
{
Enter_Method_Silent();
auto senderPos = senderPos_.getPositionAt();
auto receiverPos = receiverPos_.getPositionAt();
double senderHeight = senderPos.z;
double receiverHeight = receiverPos.z;
ASSERT(senderHeight > 0);
ASSERT(receiverHeight > 0);
std::vector<std::pair<double, double>> potentialObstacles; /**< linear position of each obstructing vehicle along (senderPos--receiverPos) */
simtime_t sStart = s.getSendingStart();
EV << "searching candidates for transmission from " << senderPos.info() << " -> " << receiverPos.info() << " (" << senderPos.distance(receiverPos) << "meters total)" << std::endl;
if (hasGUI() && annotations) {
annotations->eraseAll(vehicleAnnotationGroup);
drawVehicleObstacles(sStart);
annotations->drawLine(senderPos, receiverPos, "blue", vehicleAnnotationGroup);
}
double x1 = std::min(senderPos.x, receiverPos.x);
double x2 = std::max(senderPos.x, receiverPos.x);
double y1 = std::min(senderPos.y, receiverPos.y);
double y2 = std::max(senderPos.y, receiverPos.y);
for (auto o : vehicleObstacles) {
auto obstacleAntennaPositions = o->getInitialAntennaPositions();
double l = o->getLength();
double w = o->getWidth();
double h = o->getHeight();
auto hp_approx = o->getMobility()->getPositionAt(simTime());
EV << "checking vehicle in proximity of " << hp_approx.info() << " with height: " << h << " width: " << w << " length: " << l << endl;
if (!o->maybeInBounds(x1, y1, x2, y2, sStart)) {
EV_TRACE << "bounding boxes don't overlap: ignore" << std::endl;
continue;
}
// check if this is either the sender or the receiver
bool ignoreMe = false;
for (auto obstacleAntenna : obstacleAntennaPositions) {
if (obstacleAntenna.isSameAntenna(senderPos_)) {
EV_TRACE << "...this is the sender: ignore" << std::endl;
ignoreMe = true;
}
if (obstacleAntenna.isSameAntenna(receiverPos_)) {
EV_TRACE << "...this is the receiver: ignore" << std::endl;
ignoreMe = true;
}
}
if (ignoreMe) continue;
// this is a potential obstacle
double p1d = o->getIntersectionPoint(senderPos, receiverPos, sStart);
double maxd = senderPos.distance(receiverPos);
if (!std::isnan(p1d) && p1d > 0 && p1d < maxd) {
auto it = potentialObstacles.begin();
while (true) {
if (it == potentialObstacles.end()) {
potentialObstacles.emplace_back(p1d, h);
break;
}
if (it->first == p1d) { // omit double entries
EV << "two obstacles at same distance " << it->first << " == " << p1d << " height: " << it->second << " =? " << h << std::endl;
break;
}
if (it->first > p1d) {
potentialObstacles.insert(it, std::make_pair(p1d, h));
break;
}
++it;
}
EV << "\tgot obstacle in 2d-LOS, " << p1d << " meters away from sender" << std::endl;
Coord hitPos = senderPos + (receiverPos - senderPos) / senderPos.distance(receiverPos) * p1d;
if (hasGUI() && annotations) {
annotations->drawLine(senderPos, hitPos, "red", vehicleAnnotationGroup);
}
}
}
return potentialObstacles;
}
void VehicleObstacleControl::drawVehicleObstacles(const simtime_t& t) const
{
for (auto o : vehicleObstacles) {
annotations->drawPolygon(o->getShape(t), "black", vehicleAnnotationGroup);
}
}
| 12,651 | 33.010753 | 183 | cc |
null | AICP-main/veins/src/veins/modules/obstacle/VehicleObstacleControl.h | //
// Copyright (C) 2006-2018 Christoph Sommer <[email protected]>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#pragma once
#include <list>
#include "veins/veins.h"
#include "veins/base/utils/AntennaPosition.h"
#include "veins/base/utils/Coord.h"
#include "veins/modules/obstacle/Obstacle.h"
#include "veins/modules/world/annotations/AnnotationManager.h"
#include "veins/base/utils/Move.h"
#include "veins/modules/obstacle/MobileHostObstacle.h"
namespace veins {
class Signal;
/**
* VehicleObstacleControl models moving obstacles that block radio transmissions.
*
* Each Obstacle is a polygon.
* Transmissions that cross one of the polygon's lines will have
* their receive power set to zero.
*/
class VEINS_API VehicleObstacleControl : public cSimpleModule {
public:
~VehicleObstacleControl() override;
void initialize(int stage) override;
int numInitStages() const override
{
return 2;
}
void finish() override;
void handleMessage(cMessage* msg) override;
void handleSelfMsg(cMessage* msg);
const MobileHostObstacle* add(MobileHostObstacle obstacle);
void erase(const MobileHostObstacle* obstacle);
/**
* get distance and height of potential obstacles
*/
std::vector<std::pair<double, double>> getPotentialObstacles(const AntennaPosition& senderPos, const AntennaPosition& receiverPos, const Signal& s) const;
/**
* compute attenuation due to (single) vehicle.
* Calculate impact of vehicles as obstacles according to:
* M. Boban, T. T. V. Vinhoza, M. Ferreira, J. Barros, and O. K. Tonguz: 'Impact of Vehicles as Obstacles in Vehicular Ad Hoc Networks', IEEE JSAC, Vol. 29, No. 1, January 2011
*
* @param h1: height of sender
* @param h2: height of receiver
* @param h: height of obstacle
* @param d: distance between sender and receiver
* @param d1: distance between sender and obstacle
* @param attenuationPrototype: a prototype Signal for constructing a Signal containing the attenuation factors for each frequency
*/
static Signal getVehicleAttenuationSingle(double h1, double h2, double h, double d, double d1, Signal attenuationPrototype);
/**
* compute attenuation due to vehicles.
* Calculate impact of vehicles as obstacles according to:
* M. Boban, T. T. V. Vinhoza, M. Ferreira, J. Barros, and O. K. Tonguz: 'Impact of Vehicles as Obstacles in Vehicular Ad Hoc Networks', IEEE JSAC, Vol. 29, No. 1, January 2011
*
* @param dz_vec: a vector of (distance, height) referring to potential obstacles along the line of sight, starting with the sender and ending with the receiver
* @param attenuationPrototype: a prototype Signal for constructing a Signal containing the attenuation factors for each frequency
*/
static Signal getVehicleAttenuationDZ(const std::vector<std::pair<double, double>>& dz_vec, Signal attenuationPrototype);
protected:
AnnotationManager* annotations;
using VehicleObstacles = std::list<MobileHostObstacle*>;
VehicleObstacles vehicleObstacles;
AnnotationManager::Group* vehicleAnnotationGroup;
void drawVehicleObstacles(const simtime_t& t) const;
};
class VEINS_API VehicleObstacleControlAccess {
public:
VehicleObstacleControlAccess()
{
}
VehicleObstacleControl* getIfExists()
{
return dynamic_cast<VehicleObstacleControl*>(getSimulation()->getModuleByPath("vehicleObstacles"));
}
};
} // namespace veins
| 4,279 | 36.876106 | 180 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.