endpoint.html


001| '''Crossbar Switch Simulation - End Points.
001| 
001| Classes:
001|     PhoneNumber                 ~abstraction of a phone number
001| 
001|     SwitchEndPoint              ~end point base class
001|     SubscriberLine              ~subscriber line end point
001|     DialRegister                ~dial register end point
001| 
001|     TrunkEndPoint               ~trunk end point base class
001|     RemoteTrunk                 ~remote trunk end point
001|     LocalTrunk                  ~local trunk end point (2 required)
001|     InterOfficeTrunk            ~connects two local phones
001| 
001| '''

002| ####################################################################################################
003| from random import randint, choice
004| from logger import logger
005| from goodies import KWARG, typename, makefilename
006| from basics import MarkerMessage
007| ####################################################################################################
008| BasePath = r'C:\CJS\prj\Python\ws\xbar'
009| Log = logger('EndPoint')
010| 
011| 
012| ##------------------------------------------------------------------------------------------------##
013| AreaCodes = [
014|     (2,0,2), (2,1,3),
015|     (3,0,7), (3,1,5),
016|     (4,0,5), (4,1,2),
017|     (5,0,4), (5,1,8), (5,5,5),
018|     (6,5,1), (6,1,2),
019|     (7,0,8), (7,1,7),
020|     (8,0,0), (8,8,8),
021|     (9,4,2), (9,8,3), (9,9,9),
022| ]
023| 
024| 
025| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
026| class PhoneNumber (tuple):
027|     '''Implements a dialed phone number. (Number is randomly generated.)'''
028| 
029|     def __new__ (cls, number=None, extra=None):
030|         if number is not None:
031|             return super().__new__(cls, number)
032| 
033|         # Generate a random phone number...
034|         ac = choice(AreaCodes)
035|         tail = [randint(0,9) for _ in range(5)]
036|         nbr = [*ac, randint(2,9), randint(2,9), *tail] #TODO: restrict prefixes!
037|         return super().__new__(cls, nbr)
038| 
039|     def __init__ (self, number=None, extra=None):
040|         super().__init__()
041|         self.extra = extra if extra is not None else []
042| 
043|     @property
044|     def areacode (self): return self[0:3]
045| 
046|     @property
047|     def prefix (self): return self[3:6]
048| 
049|     @property
050|     def digits (self): return self[6:]
051| 
052|     @property
053|     def trunk_tens (self):
054|         '''Select trunk tens group.'''
055|         return ()
056| 
057|     @property
058|     def trunk_units (self):
059|         '''Select trunk units group.'''
060|         if self.prefix[0] in [0,1,2,3,4,5]:
061|             return (0,1,2)
062|         if self.prefix[0] in [6]:
063|             return (3,4)
064|         if self.prefix[0] in [9]:
065|             return (7,)
066|         return (5,6)
067| 
068|     def __repr__ (self):
069|         return f'<{typename(self)} @{id(self):012x}>'
070| 
071|     def __str__ (self):
072|         return '{0}{1}{2}-{3}{4}{5}-{6}{7}{8}{9}'.format(*self)
073| 
074| 
075| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
076| class SwitchEndPoint:
077|     '''Switch End Point (base class).
077| 
077| Implements a Subscriber Line or Trunk connected to the switch.
077| 
077| Class Properties:
077|     Messages            -list: MarkerMessages to Marker
077|     Tag                 -str: end point type
077| 
077| Properties:
077|     status              -str: current status
077|     link_id             -int: switch line## or trunk##
077|     props               -dict: extra properties
077|     msg_queue           -list: incoming MarkerMessages
077|     call_list           -list: calls made
077| 
077| Methods:
077|     reset               -reset end point
077|     tick                -timeslice for end point
077|     receive             -messages for the end point
077| '''

078|     Messages = []
079|     Tag = '<endpoint>'
080|     Src = MarkerMessage.UNKNOWN
081| 
082|     Idle = 0
083|     OffHook = 1
084|     Working = 2
085|     Ready = 3
086|     Dialing = 4
087|     Ringing = 5
088|     Connected =  6
089|     Done = 7
090|     WaitingForDialtone = 8
091|     WaitingForConnection = 9
092| 
093|     StatusText = [
094|         'Idle',
095|         'Off-Hook',
096|         'Working',
097|         'Ready',
098|         'Dialing',
099|         'Ringing',
100|         'Connected',
101|         'Done',
102|         'W4Dialtone',
103|         'W4Connection',
104|     ]
105| 
106|     def __init__ (self, link_id:int, **props):
107|         '''New SwitchEndPoint instance.'''
108|         # Validate input...
109|         assert 0 <= link_id <= 99, ValueError(f'Invalid Line ID: "{link_id}"')
110|         # Initialize...
111|         self.link_id = link_id
112|         self.props = dict(props)
113|         self.call_list = []                 # list of all calls made or received
114|         self.msg_queue = []                 # list of messages to end point
115|         self.status = SwitchEndPoint.Idle   # current status
116| 
117|     def reset (self):
118|         '''Reset the end point.'''
119|         self.msg_queue = []
120|         self.status = SwitchEndPoint.Idle
121| 
122|     def receive (self, msg):
123|         '''Receive a message for the end point.'''
124|         self.msg_queue.append(msg)
125| 
126|     def send (self, tick_id, msg_type, content=''):
127|         '''Send a message to the Marker.'''
128|         msg = MarkerMessage(self.Src, self.link_id, tick_id, msg_type, content)
129|         self.Messages.append(msg)
130| 
131|     def tick (self, tick_id):
132|         '''Timeslice for end point.'''
133|         Log.trace(f'[{tick_id:06d}] L{self.link_id:02d} <tick> {self.StatusText[self.status]}')
134| 
135|     def __repr__ (self):
136|         '''Debug string.'''
137|         return f'<{typename(self)} {self.Tag}.{self.link_id:02d} @{id(self):012x}>'
138| 
139|     def __str__ (self):
140|         '''Print string.'''
141|         return f'{self.Tag}.{self.link_id:02d} {self.StatusText[self.status]}'
142| 
143| 
144| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
145| class SubscriberLine (SwitchEndPoint):
146|     '''Subscriber Line.
146| 
146| Implements a subscriber phone line.
146| 
146| Class Properties:
146|     Tag                 -str: "Subscriber"
146|     Subscribers         -dict: dictionary of subscribers
146| 
146| Properties:
146|     status              -str: current status
146|     line_id             -int: switch line## or trunk##
146|     props               -dict: extra properties
146|     msg_queue           -list: incoming MarkerMessages
146|     call_list           -list: calls made
146| 
146| Methods:
146|     reset               -reset end point
146|     tick                -timeslice for end point
146|     receive             -messages for the end point
146|     call_number         -force a phone call
146| '''

147|     Tag = 'Subscriber'
148|     Src = MarkerMessage.LINE
149|     Subscribers = {}
150| 
151|     def __init__ (self, line_id:int, line_type='normal', **props):
152|         '''New SubscriberLine instance.'''
153|         super().__init__(line_id, **props)
154|         self.line_type = line_type
155| 
156|         # Subscriber Line simulation properties...
157|         self.call_wait_min = KWARG('call_wait_min',  25, int, props)
158|         self.call_wait_max = KWARG('call_wait_max', 150, int, props)
159|         self.call_time_min = KWARG('call_time_min',  20, int, props)
160|         self.call_time_max = KWARG('call_time_max', 200, int, props)
161|         self.dial_wait_min = KWARG('dial_wait_min',   2, int, props)
162|         self.dial_wait_max = KWARG('dial_wait_max',   7, int, props)
163|         self.ring_wait_min = KWARG('ring_wait_min',   2, int, props)
164|         self.ring_wait_max = KWARG('ring_wait_max',   7, int, props)
165| 
166|         # Initialize...
167|         self.reset()
168| 
169|         # Add to subscribers list...
170|         SubscriberLine.Subscribers[self.link_id] = self
171| 
172|     def reset (self):
173|         '''Reset the line.'''
174|         super().reset()
175|         self.call_phone_nmbr = None
176|         self.call_start_tick = None
177|         self.call_quit_tick  = 100
178|         self.next_call_tick  = randint(self.call_wait_min, self.call_wait_max)
179|         self.dial_delay_tick = 3
180|         self.ring_delay_tick = 8
181| 
182|     def tick (self, tick_id):
183|         '''Timeslice for Subscriber Line.'''
184|         super().tick(tick_id)
185| 
186|         # Process any messages sent to us...
187|         while self.msg_queue:
188|             # Get next message...
189|             msg = self.msg_queue.pop(0)
190|             Log.trace(msg)
191| 
192|             # Dispatch on Message Type...
193|             match msg.msgtype:
194|                 case MarkerMessage.RINGING:
195|                     self.call_phone_nmbr = msg.content
196|                     self.ring_delay_tick = tick_id + randint(self.ring_wait_min, self.ring_wait_max)
197|                     self.status = SwitchEndPoint.Ringing
198|                     Log.debug(f'[{tick_id:06d}] {self} RINGING (ring delay: {self.ring_delay_tick})')
199| 
200|                 case MarkerMessage.DIALTONE:
201|                     self.dial_delay_tick = tick_id + randint(self.dial_wait_min, self.dial_wait_max)
202|                     self.status = SwitchEndPoint.Dialing
203|                     Log.debug(f'[{tick_id:06d}] {self} DIALTONE (dial delay: {self.dial_delay_tick})')
204| 
205|                 case MarkerMessage.CONNECT:
206|                     self.call_start_tick = tick_id
207|                     #NOTE: override if this is answered call?
208|                     self.call_quit_tick = tick_id + randint(self.call_time_min, self.call_time_max)
209|                     self.status = SwitchEndPoint.Connected
210|                     Log.debug(f'[{tick_id:06d}] {self} CONNECT (call quit: {self.call_quit_tick})')
211| 
212|                 case MarkerMessage.OFFHOOK:
213|                     #TODO: call cleanup
214|                     elapsed = tick_id - self.call_start_tick
215|                     rcd = (tick_id, self.call_phone_nmbr, self.call_start_tick, elapsed)
216|                     self.call_list.append(rcd)
217|                     self.next_call_tick = tick_id + randint(self.call_wait_min, self.call_wait_max)
218|                     self.status = SwitchEndPoint.Idle
219|                     Log.debug(f'[{tick_id:06d}] {self} OFFHOOK')
220| 
221|                 case _:
222|                     # Unexpected message type...
223|                     raise RuntimeError(f'[{tick_id:06d}]Line[{self.link_id:2d}] Unknown Message type: {m} {m!r}')
224| 
225|         # Act (depending on our status)...
226|         match self.status:
227| 
228|             case SwitchEndPoint.Idle:
229|                 # If it's time to make a call, go offhook...
230|                 if self.next_call_tick <= tick_id:
231|                     # Send message to marker...
232|                     self.send(tick_id, MarkerMessage.OFFHOOK, f'Call #{1+len(self.call_list)}')
233|                     self.status = SwitchEndPoint.WaitingForDialtone
234| 
235|             case SwitchEndPoint.Ringing:
236|                 #ATTN: Need timeout!
237|                 # If the phone is ringing, answer it...
238|                 if self.ring_delay_tick <= tick_id:
239|                     # Send message to marker...
240|                     self.send(tick_id, MarkerMessage.CONNECT, f'Answering')
241|                     self.call_quit_tick = tick_id + randint(self.call_time_min, self.call_time_max)
242|                     self.status = SwitchEndPoint.WaitingForConnection
243| 
244|             case SwitchEndPoint.WaitingForDialtone:
245|                 #ATTN: Need timeout!
246|                 ...
247| 
248|             case SwitchEndPoint.Dialing:
249|                 #ATTN: Need timeout!
250|                 self.call_phone_nmbr = PhoneNumber()
251|                 # After a delay, submit the phone number...
252|                 if self.dial_delay_tick <= tick_id:
253|                     # Send message to marker...
254|                     self.send(tick_id, MarkerMessage.INFO, self.call_phone_nmbr)
255|                     self.status = SwitchEndPoint.WaitingForConnection
256| 
257|             case SwitchEndPoint.WaitingForConnection:
258|                 #ATTN: Need timeout!
259|                 ...
260| 
261|             case SwitchEndPoint.Connected:
262|                 # If it's time to end the call, hangup...
263|                 if self.call_quit_tick <= tick_id:
264|                     # Send message to marker...
265|                     self.send(tick_id, MarkerMessage.HANGUP)
266|                     self.status = SwitchEndPoint.OffHook
267| 
268|             case _:
269|                 raise RuntimeError(f'Unexpected Line status: {self.status}')
270| 
271|         return self.status
272| 
273|     def call_number (self, phone_nmbr):
274|         '''Force line to make a phone call.'''
275|         pass
276| 
277|     def __del__ (self):
278|         '''Remove Subscriber.'''
279|         if self.link_id in SubscriberLine.Subscribers:
280|             del SubscriberLine.Subscribers[self.link_id]
281| 
282|     def __str__ (self):
283|         '''Print string.'''
284|         return f'L{self.link_id:02d} ({self.StatusText[self.status]})'
285| 
286| 
287| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
288| class DialRegister (SwitchEndPoint):
289|     '''Dial Register End Point class.'''
290|     Tag = 'DialRegister'
291|     Src = MarkerMessage.REGISTER
292| 
293|     def __init__ (self, trunk_id:int, **props):
294|         '''New DialRegister instance.'''
295|         super().__init__(trunk_id, **props)
296| 
297|         # Dial Register simulation properties...
298|         self.timeout_ticks = KWARG('timeout_ticks', 25, int, props)
299|         self.dial_wait_min = KWARG('dial_wait_min',  2, int, props)
300|         self.dial_wait_max = KWARG('dial_wait_max',  7, int, props)
301| 
302|         # Initialize...
303|         self.reset()
304| 
305|     def reset (self):
306|         '''Reset the Register.'''
307|         super().reset()
308|         self.dialed_number = None
309|         self.subscriber_line = None
310|         self.dial_delay_tick = 0
311| 
312|     def clear (self):
313|         '''Clear the Register.'''
314|         self.dialed_number = None
315|         self.subscriber_line = None
316|         self.dial_delay_tick = 0
317|         self.status = SwitchEndPoint.Idle
318| 
319|     def tick (self, tick_id):
320|         '''Timeslice for Dial Register.'''
321|         super().tick(tick_id)
322| 
323|         # Process any messages sent to us...
324|         while self.msg_queue:
325|             # Get next message...
326|             msg = self.msg_queue.pop(0)
327|             Log.trace(msg)
328| 
329|             # Dispatch on Message Type...
330|             match msg.msgtype:
331| 
332|                 case MarkerMessage.OFFHOOK:
333|                     self.dial_delay_tick = tick_id + 2
334|                     self.status = SwitchEndPoint.OffHook
335|                     Log.debug(f'[{tick_id:06d}] {self} OFFHOOK')
336| 
337|                 case MarkerMessage.CALL:
338|                     self.subscriber_line = msg.content[0]
339|                     self.dialed_number = msg.content[1]
340|                     self.dial_delay_tick = tick_id + randint(self.dial_wait_min, self.dial_wait_max)
341|                     self.status = SwitchEndPoint.Working
342|                     Log.debug(f'[{tick_id:06d}] {self} CALL {self.dialed_number}')
343| 
344|                 case MarkerMessage.HANGUP:
345|                     self.clear()
346|                     Log.debug(f'[{tick_id:06d}] {self} HANGUP')
347| 
348|                 case _:
349|                     # Unexpected message type...
350|                     raise RuntimeError(f'[{tick_id:06d}]Line[{self.link_id:2d}] Unknown Message type: {m} {m!r}')
351| 
352|         # Act (depending on our status)...
353|         match self.status:
354| 
355|             case SwitchEndPoint.Idle:
356|                 pass
357| 
358|             case SwitchEndPoint.OffHook:
359|                 if self.dial_delay_tick <= tick_id:
360|                     self.send(tick_id, MarkerMessage.DIALTONE)
361|                     self.dial_delay_tick = tick_id + self.timeout_ticks
362|                     self.status = SwitchEndPoint.Ready
363| 
364|             case SwitchEndPoint.Ready:
365|                 if self.dial_delay_tick <= tick_id:
366|                     # Timeout...
367|                     self.send(tick_id, MarkerMessage.SYSTEM, 'Dialtone Timeout')
368|                     self.clear()
369| 
370|             case SwitchEndPoint.Working:
371|                 if self.dial_delay_tick <= tick_id:
372|                     ttens = self.dialed_number.trunk_tens
373|                     tunits = self.dialed_number.trunk_units
374|                     # Create INFO payload...
375|                     inf = (self.dialed_number, self.subscriber_line, ttens, tunits)
376|                     # Send INFO Message...
377|                     self.send(tick_id, MarkerMessage.INFO, inf)
378|                     self.call_list.append((tick_id, inf))
379|                     # Dial register is done...
380|                     self.dial_delay_tick = tick_id + self.timeout_ticks
381|                     self.status = SwitchEndPoint.Done
382| 
383|             case SwitchEndPoint.Done:
384|                 if self.dial_delay_tick <= tick_id:
385|                     # Timeout...
386|                     self.send(tick_id, MarkerMessage.SYSTEM, 'Dialtone Timeout')
387|                     self.clear()
388| 
389|             case _:
390|                 raise RuntimeError(f'Unexpected DialRegister status: {self.status}')
391| 
392|         return self.status
393| 
394|     def __str__ (self):
395|         '''Print string.'''
396|         return f'DR{self.link_id:02d} ({self.StatusText[self.status]})'
397| 
398| 
399| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
400| class TrunkEndPoint (SwitchEndPoint):
401|     '''Trunk End Point (base class).'''
402|     Trunks = {}
403| 
404|     def __init__ (self, trunk_id:int, **props):
405|         '''New Trunk instance.'''
406|         super().__init__(trunk_id, **props)
407| 
408|         # Remote Trunk simulation properties...
409|         self.timeout_ticks = KWARG('timeout_ticks', 25, int, props)
410|         self.conn_wait_min = KWARG('conn_wait_min',  5, int, props)
411|         self.conn_wait_max = KWARG('conn_wait_max', 13, int, props)
412| 
413|         # Initialize...
414|         self.reset()
415| 
416| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
417| class RemoteTrunk (TrunkEndPoint):
418|     '''Remote Trunk End Point class.'''
419|     Tag = 'RemoteTrunk'
420|     Src = MarkerMessage.REMOTE
421| 
422|     def __init__ (self, trunk_id:int, **props):
423|         '''New RemoteTrunk instance.'''
424|         super().__init__(trunk_id, **props)
425| 
426|     def reset (self):
427|         '''Reset the Trunk.'''
428|         super().reset()
429|         self.call_info = None
430|         self.subscriber_line = None
431|         self.conn_delay_tick = 0
432| 
433|     def clear (self):
434|         '''Clear the Trunk.'''
435|         self.call_info = None
436|         self.subscriber_line = None
437|         self.conn_delay_tick = 0
438|         self.status = SwitchEndPoint.Idle
439| 
440|     def tick (self, tick_id):
441|         '''Timeslice for Trunk.'''
442|         super().tick(tick_id)
443| 
444|         # Process any messages sent to us...
445|         while self.msg_queue:
446|             # Get next message...
447|             msg = self.msg_queue.pop(0)
448|             Log.trace(msg)
449| 
450|             # Dispatch on Message Type...
451|             match msg.msgtype:
452| 
453|                 case MarkerMessage.CALL:
454|                     self.subscriber_line = msg.content[0]
455|                     self.call_info = msg.content[1]
456|                     self.conn_delay_tick = tick_id + randint(self.conn_wait_min, self.conn_wait_max)
457|                     self.status = SwitchEndPoint.WaitingForConnection
458|                     Log.debug(f'[{tick_id:06d}] {self} CALL {self.call_info}')
459| 
460|                 case MarkerMessage.CONNECT:
461|                     Log.debug(f'[{tick_id:06d}] {self} CONNECT {self.call_info}')
462| 
463|                 case MarkerMessage.HANGUP:
464|                     rcd = (tick_id, self.subscriber_line, self.call_info)
465|                     self.call_list.append(rcd)
466|                     self.clear()
467|                     Log.debug(f'[{tick_id:06d}] {self} HANGUP')
468| 
469|                 case _:
470|                     # Unexpected message type...
471|                     raise RuntimeError(f'[{tick_id:06d}]Line[{self.link_id:2d}] Unknown Message type: {m} {m!r}')
472| 
473|         # Act (depending on our status)...
474|         match self.status:
475| 
476|             case SwitchEndPoint.Idle:
477|                 pass
478| 
479|             case SwitchEndPoint.WaitingForConnection:
480|                 if self.conn_delay_tick <= tick_id:
481|                     self.send(tick_id, MarkerMessage.CONNECT)
482|                     self.status = SwitchEndPoint.Connected
483| 
484|             case SwitchEndPoint.Connected:
485|                 pass
486| 
487|             case _:
488|                 raise RuntimeError(f'Unexpected DialRegister status: {self.status}')
489| 
490|         return self.status
491| 
492|     def __str__ (self):
493|         '''Print string.'''
494|         return f'T{self.link_id:02d} ({self.StatusText[self.status]})'
495| 
496| 
497| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
498| class LocalTrunk (TrunkEndPoint):
499|     '''Local Trunk End Points class.'''
500|     Tag = 'LocalTrunk'
501|     Src = MarkerMessage.LOCAL
502| 
503|     def __init__ (self, trunk_id:int, **props):
504|         '''New LocalTrunk instance.'''
505|         super().__init__(trunk_id, **props)
506|         #TODO: how does this work?
507|         #ATTN: need to connect both trunks to each other
508| 
509|     def reset (self):
510|         '''Reset the Trunk.'''
511|         super().reset()
512| 
513| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
514| class InterOfficeTrunk:
515|     '''Pair of interconnected Local Trunks for interoffice calls.'''
516| 
517|     def __init__ (self, trunk_id:int, **props):
518|         '''New InterOfficeTrunk instance.'''
519|         self.trunk1 = LocalTrunk(trunk_id_1)
520|         self.trunk2 = LocalTrunk(trunk_id_2)
521|         #ATTN: Marker needs to recognize IOTrunk is different - not an endpoint!
522| 
523|     @property
524|     def trk1 (self): return self.trunk1
525| 
526|     @property
527|     def trk2 (self): return self.trunk2
528| 
529|     def reset (self):
530|         '''Reset both trunks.'''
531|         self.trunk1.reset()
532|         self.trunk2.reset()
533| 
534|     def __repr__ (self):
535|         '''Debug string.'''
536|         return f'<{typename(self)} @{id(self):012x}>'
537| 
538|     def __str__ (self):
539|         s1 = str(self.trk1)
540|         '''Print string.'''
541|         s2 = str(self.trk2)
542|         return f'{s1}\n{s2}'
543| 
544| 
545| ####################################################################################################
546| '''eof'''
547|