| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- # Copyright 2023 Modelling, Simulation and Design Lab (MSDL)
- # at the University of Antwerp (http://msdl.uantwerpen.be/).
- #
- # Licensed under the GNU Public License v3 (the "License");
- # you may not use this file except in compliance with the
- # License. You may obtain a copy of the License at
- # https://www.gnu.org/licenses/gpl-3.0.en.html
- #
- # Unless required by applicable law or agreed to in writing,
- # software distributed under the License is distributed on an
- # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
- # either express or implied. See the License for the specific
- # language governing permissions and limitations under the
- # License.
- from pytcore.util.seeded_random import Random
- from pytcore.tcore.control_primitive import ControlPrimitive
- from pytcore.tcore.messages import Cancel, TransformationException, NIL_PACKET
- class Selector(ControlPrimitive):
- '''
- Selects a packet randomly.
- '''
- def __init__(self):
- '''
- Selects a packet randomly.
- '''
- super(Selector, self).__init__()
- self.exclusions = []
- def success_in(self, packet):
- '''
- Receives a successful packet
- '''
- self.exception = None
- self.is_success = False
- self.success.append(packet)
- def fail_in(self, packet):
- '''
- Receives a failed packet
- '''
- self.exception = None
- self.is_success = False
- self.fail.append(packet)
- def reset(self):
- super(Selector, self).reset()
- self.exclusions = []
- def select(self):
- '''
- Selects a packet randomly from the success list.
- If the success list is empty, then from the fail list.
- '''
- self.exception = None
- self.is_success = False
- if len(self.success) > 0:
- self.is_success = True
- packet = Random.choice(self.success)
- self.exclusions.append(packet.current)
- return packet
- elif len(self.fail) > 0:
- self.is_success = False
- return Random.choice(self.fail)
- else:
- self.is_success = False
- #TODO: This should be a TransformationLanguageSpecificException
- self.exception = TransformationException('No packet was received')
- self.exception.packet = NIL_PACKET
- return NIL_PACKET
- def cancel(self):
- '''
- Produces a cancel event and resets its state
- '''
- c = Cancel()
- c.exclusions = self.exclusions
- self.reset()
- return c
|