Alejandro Acuña
2024-07-30 65a64a81d30f00f1fffd5da6866850e1308e1135
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
'***************************************************************************
'* Class ClassSosPhone                                                     *
'*                                                                         *
'* This class manages the communication with the E301 module.              *
'*                                                                         *
'* EQUITEL C.V. February 2007                                         ALMDI*
'***************************************************************************
 
Imports VB = Microsoft.VisualBasic
Imports System.Object
Imports System.Net.NetworkInformation
 
 
 
Public Class ClassSosPhone
 
#Region "Enumerated types"
    Public Enum Status
        Standby
        AudioOn
        ToneOn
        MessageOn
        Sent_ORD_FON_ON
        Sent_ORD_FON_OFF
        Sent_ORD_VOZ_ON
        Sent_ORD_VOZ_OFF
        Sent_ORD_TON_ON
        Sent_ORD_TON_OFF
        Sent_ORD_ESC_IO
        Sent_ORD_LEC_IO
        Sent_ORD_ADJ_VOL
        Sent_ORD_TST_MAN
        Sent_ORD_TST_FON
        Sent_ORD_ECO_ON
        Sent_ORD_ECO_OFF
        Sent_ORD_ECO_ACT_ON
        Sent_ORD_ECO_ACT_OFF
        Sent_ORD_ADJ_MIC
        Sent_ORD_TST_WD
        Received_DEM_USE
        Received_DEM_SER
        Received_ENV_ALA
        Received_ACK_VOZ_ON
        Received_ACK_VOZ_OFF
        Received_ACK_TON_ON
        Received_ACK_TON_OFF
        Received_ACK_FON_ON
        Received_ACK_FON_OFF
        Received_ACK_ESC_IO
        Received_ACK_LEC_IO
        Received_ACK_ADJ_VOL
        Received_RES_TST_MAN
        Received_RES_TST_FON
        Received_ACK_ECO_ON
        Received_ACK_ECO_OFF
        Received_ACK_ECO_ACT_ON
        Received_ACK_ECO_ACT_OFF
        Received_ACK_ADJ_MIC
        Received_ACK_TST_WD
    End Enum
 
    Public Enum AudioMessageType
        ReceivedCall
        OutOfService
    End Enum
 
    Public Enum ToneType
        Ringing
        Occupied
    End Enum
#End Region
 
#Region "Fields and definitions"
    'UDP RTP receiving port of the E301 module
    Private Const mRTPPort As Integer = 6666
    'TCP Control port of the E301
    Private Const mCTRLPort As Integer = 3000
    'Time between attempts when sending any command (in seconds)
    Private Const mAttemptsTime As Integer = 5
    'Number of Attempts before given the E301 as 'dead'
    Private Const MaxtemptsNumer As Byte = 3
    'Time elapsed between "audio on" command sents when in "audio on" mode
    Private Const mAudioReactivationTime As Long = 60000 'miliseconds
 
    'Ip of the E301 module
    Private mIp As String
    'The number automatically assigned when the object is created
    Private mNumber As Integer
    'User description to identify the SosPhone
    Private mDescription As String
    'Indicates if the TCP connexion with the E301 has been established
    Private mConnected As Boolean
    'The compueter is trying to establish a connection with the E301
    Private mTryingToConnect As Boolean
    'Internal status of the SosPhone Object
    Private mStatus As Status
    'Indicates if the internal status has been read 
    Private mUpdatedAlarms As Boolean
    'Alarms status of the master phone
    Private mMasterPhoneSatatus As Byte
    'Alarms status of the slave phone
    Private mSlavePhoneStatus As Byte
    'Output Volume level of the master phone
    Private mMasterPhoneVolume As Byte
    'Output Volume level of the slave phone
    Private mSlavePhoneVolume As Byte
    'Last audio loopback test result
    Private mAudioTestResult As Byte
    'Status of the last read of the auxiliary port
    Private mAuxiliaryPort As Byte
#End Region
 
#Region "Embeded objects"
    Private WithEvents mTCPClient As ClassTCPClient
    Public WithEvents AudioWindow As New frmAudio
 
    'Timer to re-send audio on (or other) commands at fixed intervals to keep the
    'E301 audio active. (For security purposes, once received an "audio on" order, 
    'the E301 keeps the audio active for 2 minutes only. You must reactivate it before
    'this period elapses to keep the audio active)
    Private Class ClassReactivationTimer
        Inherits System.Timers.Timer
        Public mData As Byte()
        Public mCommand As Byte
        Public mMasterOrSlave As Byte
        Public TxtLog As String
 
        Public Sub Configure(ByVal Command As Byte, ByVal MasterOrSlave As Byte, ByVal ParamArray Data() As Byte)
            mCommand = Command
            mMasterOrSlave = MasterOrSlave
            mData = Data
        End Sub
    End Class
 
    Private WithEvents ReactivationTimer As New ClassReactivationTimer
#End Region
 
#Region "Properties"
 
    Public ReadOnly Property IP() As String
        Get
            Return mIp
        End Get
    End Property
 
    Public ReadOnly Property Number() As String
        Get
            Return Format(mNumber, "000")
        End Get
    End Property
 
    Public ReadOnly Property Description() As String
        Get
            Return mDescription
        End Get
    End Property
 
    Public ReadOnly Property Name() As String
        Get
            Dim S As String
            S = "P_" + Format(mNumber, "000") + " -> " + mIp + vbCrLf
            S = S + "   " + mDescription + vbCrLf
            If mConnected Then
                S = S + "   Connected"
            Else
                S = S + "   Not connected"
            End If
            Return S
        End Get
    End Property
 
    Public ReadOnly Property LowBattery() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H40) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property PowerFail() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H8) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property MasterDoorAlarm() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H20) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property MasterAudioOn() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H4) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property MasterToneOn() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H2) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property MasterAudioMessageOn() As Boolean
        Get
            Return ((mMasterPhoneSatatus And &H1) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property SlaveDoorAlarm() As Boolean
        Get
            Return ((mSlavePhoneStatus And &H20) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property SlaveAudioOn() As Boolean
        Get
            Return ((mSlavePhoneStatus And &H4) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property SlaveToneOn() As Boolean
        Get
            Return ((mSlavePhoneStatus And &H2) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property SlaveAudioMessageOn() As Boolean
        Get
            Return ((mSlavePhoneStatus And &H1) <> 0)
        End Get
    End Property
 
    Public ReadOnly Property Connected() As Boolean
        Get
            Return mConnected
        End Get
    End Property
 
    Public ReadOnly Property AudioTestResult() As String
        Get
            Select Case mAudioTestResult
                Case TST_OK : Return "OK"
                Case TST_FAIL : Return "FAIL"
                Case Else : Return "¿?"
            End Select
        End Get
    End Property
 
    Public ReadOnly Property MasterVolume() As Byte
        Get
            Return mMasterPhoneVolume
        End Get
    End Property
 
    Public ReadOnly Property SlaveVolume() As Byte
        Get
            Return mSlavePhoneVolume
        End Get
    End Property
 
    Public ReadOnly Property AuxiliaryPort() As Byte
        Get
            Return mAuxiliaryPort
        End Get
    End Property
 
    Public ReadOnly Property UpdatedAlarms() As Boolean
        Get
            Return mUpdatedAlarms
        End Get
    End Property
#End Region
 
#Region "Events"
    Public Event Log As TxtEventHandler
    Public Event ConnectionSuccesful As EventHandler
    Public Event ConnectionFailed As EventHandler
    Public Event AlarmsReceived As EventHandler
    Public Event AuxilaryPortRead As ByteEventHandler
    Public Event AudioTestCompleted As ByteEventHandler
    Public Event MaitenanceTestCompleted As EventHandler
    Public Event IncomingUserCall As ByteEventHandler
    Public Event IncomingServiceCall As ByteEventHandler
 
    Protected Overridable Sub OnLog(ByVal Txt As String)
        Dim e As New TxtEventArgs
        e.TxtLog = Txt
        RaiseEvent Log(Me, e)
    End Sub
 
    Protected Overridable Sub OnConnectionSuccesful()
        RaiseEvent ConnectionSuccesful(Me, New EventArgs())
    End Sub
 
    Protected Overridable Sub OnConnectionFailed()
        RaiseEvent ConnectionFailed(Me, New EventArgs())
    End Sub
 
    Protected Overridable Sub OnAlarmsReceived()
        RaiseEvent AlarmsReceived(Me, New EventArgs())
    End Sub
 
    Protected Overridable Sub OnAuxiliaryPortRead(ByVal B As Byte)
        Dim e As New ByteEventArgs
        e.Data = B
        RaiseEvent AuxilaryPortRead(Me, e)
    End Sub
 
    Protected Overridable Sub OnAudioTestCompleted(ByVal B As Byte)
        Dim e As New ByteEventArgs
        e.Data = B
        RaiseEvent AudioTestCompleted(Me, e)
    End Sub
 
    Protected Overridable Sub OnMaintenanceTestCompleted()
        RaiseEvent MaitenanceTestCompleted(Me, New EventArgs())
    End Sub
 
    Protected Overridable Sub OnIncomingUserCall(ByVal B As Byte)
        Dim e As New ByteEventArgs
        e.Data = B
        RaiseEvent IncomingUserCall(Me, e)
    End Sub
 
    Protected Overridable Sub OnIncomingServiceCall(ByVal B As Byte)
        Dim e As New ByteEventArgs
        e.Data = B
        RaiseEvent IncomingServiceCall(Me, e)
    End Sub
 
#End Region
 
#Region "Methods"
 
#Region "Constructor"
    Public Sub New(ByVal Ip As String, ByVal Number As Integer, ByVal Description As String)
        mIp = Ip
        mNumber = Number
        mDescription = Description
        mConnected = False
        mTryingToConnect = False
        mStatus = Status.Standby
        ReactivationTimer.Interval = mAudioReactivationTime
        ReactivationTimer.Enabled = False
        ReactivationTimer.AutoReset = True
        mUpdatedAlarms = False
        mTCPClient = New ClassTCPClient(mIp, mCTRLPort)
    End Sub
#End Region
 
#Region "TCP Connexion"
 
    Public Sub TryToConnect()
        'Initiates the connection process. After some time, the mTCPClient object
        'will raise an event indicating if the connection has been succesful or not.
        If Not mConnected Then
            mTCPClient.HostIP = mIp
            mTCPClient.HostPort = mCTRLPort
            mTryingToConnect = True
            mTCPClient.TryInitConnection()
        End If
    End Sub
 
    Private Sub mTCPclient_OnConnectionSuccesfull(ByVal sender As Object, ByVal e As EventArgs) Handles mTCPClient.ConnectionSuccesful
        'The mTCPClient object indicates success in the connexion
        mConnected = True
        OnConnectionSuccesful()
        OnLog("Connected to IP " + mIp)
    End Sub
 
    Private Sub mTCPclient_ConnectionFailed(ByVal sender As Object, ByVal e As EventArgs) Handles mTCPClient.ConnectionFailed
        'The mTCPClient indicates that the connection hasn't been possible. It automatically
        'tries to connect again
        mConnected = False
        OnConnectionFailed()
        OnLog("Can't connect")
        OnLog("Trying to connect again")
    End Sub
 
    Public Sub Disconnect()
        'Close the TCP Connection with the E301 module
        If mConnected Then
            mTCPClient.Disconnect()
            OnLog("Disconnected")
            mConnected = False
        End If
    End Sub
 
    Private Sub mTCPClient_ConnectionTerminated(ByVal sender As Object, ByVal e As EventArgs) Handles mTCPClient.ConnectionTerminated
        'The mTCPClient object indicates that the E301 module has closed the connection
        mConnected = False
        OnLog("Connection terminated by Sos Phone")
    End Sub
 
    Private Sub mTCPClient_DataReceived(ByVal sender As Object, ByVal e As TCPDataReceivedEventArgs) Handles mTCPClient.DataReceived
        'Some data is sent from the E301 module
        Dim i As Integer
        Dim S As String
        Dim T As String
        Dim C As Short
        '-----------------------------------------------------------------------
        'Uncomment the next lines if you want to show the content of the message 
        'in the log window
        'S = ""
        'For i = 0 To (e.Lenght - 1)
        ' T = Hex(e.Data(i))
        'T = StrDup(2 - Len(T), "0") + T
        'S = S + "[0x" + T + "] "
        'Next
        'S = "Received: " + S
        'OnLog(S)
        '-----------------------------------------------------------------------
        C = 0 ' CRC(e.Data, e.Lenght)
        'CRC Testing (for backwards compatibility purposes only...)
        If C = 0 Then
            ParseMessage(e.Data, e.Lenght)
        Else
            OnLog("CRC Mismatch!!")
        End If
    End Sub
 
    Public Sub SendMessage(ByVal Command As Byte, ByVal MasterOrSlave As Byte, ByVal ParamArray Data() As Byte)
        'Send a message to the E301 module
        'Messages are in one of the forms:
        '  +--------+---------+---------------+---------+-------+-------+
        '  | Number | Command | MasterOrSlave |Data.... | CRC_H | CRC_L |
        '  +--------+---------+---------------+---------+-------+-------+
        '
        '  +--------+---------+---------+-------+-------+
        '  | Number | Command |Data.... | CRC_H | CRC_L |
        '  +--------+---------+---------+-------+-------+
        '
        ' Number:        Not used. Maintained for backwards compatibility
        ' Command:       Indicates the action
        ' MasterOrSlave: Depending on the command, it may be directed to the master
        '                or slave phone
        ' Data:          Data needed for the command.
        ' CRC:           CRC of the message. Maintained for backwards compatibility
        '
        Dim Buf() As Byte
        Dim i As Integer
        Dim j As Integer
        Dim C As UShort, CH As Integer, CL As Integer
 
        If mConnected Then
            'Calculate the length of the message
            i = 2 + UBound(Data) + 3
            If MasterOrSlave <> 255 Then i = i + 1
            ReDim Buf(i - 1)
            'Number always 0
            Buf(0) = &H0
            Buf(1) = Command
            j = 2
            If MasterOrSlave <> 255 Then
                Buf(2) = MasterOrSlave
                j = 3
            End If
            For i = 0 To UBound(Data)
                Buf(j) = Data(i)
                j = j + 1
            Next
            'If you want you can calculate the CRC or fill it with &HFFFF
            'to indicate to the E301 module that the CRCR is not used.
            C = CRC(Buf, j) 'Calulate the CRC
            'C = &HFFFF 'Don't calculate the CRC. 
            CH = (C And &HFF00) >> 8
            Buf(j) = CH
            CL = (C And &HFF)
            Buf(j + 1) = CL
            mTCPClient.SendData(Buf)
        Else
            OnLog("Can't send message. Sos phone not connected")
        End If
    End Sub
 
    Public Sub SendMessage2(ByVal Command As Byte, ByVal MasterOrSlave As Byte, ByVal ParamArray Data() As Byte)
        'Send a message to the E301 module
        'Messages are in one of the forms:
        '  +--------+---------+---------------+---------+-------+-------+
        '  | Number | Command | MasterOrSlave |Data.... | CRC_H | CRC_L |
        '  +--------+---------+---------------+---------+-------+-------+
        '
        '  +--------+---------+---------+-------+-------+
        '  | Number | Command |Data.... | CRC_H | CRC_L |
        '  +--------+---------+---------+-------+-------+
        '
        ' Number:        Not used. Maintained for backwards compatibility
        ' Command:       Indicates the action
        ' MasterOrSlave: Depending on the command, it may be directed to the master
        '                or slave phone
        ' Data:          Data needed for the command.
        ' CRC:           CRC of the message. Maintained for backwards compatibility
        '
        Dim Buf() As Byte
        Dim i As Integer
        Dim j As Integer
        Dim C As UShort, CH As Integer, CL As Integer
 
        If mConnected Then
            'Calculate the length of the message
            i = 2 + UBound(Data) + 3
            If MasterOrSlave <> 255 Then i = i + 1
            ReDim Buf(i - 1)
            'Number always 0
            Buf(0) = &H0
            Buf(1) = Command
            j = 2
            If MasterOrSlave <> 255 Then
                Buf(2) = MasterOrSlave
                j = 3
            End If
            For i = 0 To UBound(Data)
                Buf(j) = Data(i)
                j = j + 1
            Next
            'If you want you can calculate the CRC or fill it with &HFFFF
            'to indicate to the E301 module that the CRCR is not used.
            C = CRC(Buf, j) 'Calulate the CRC
            'C = &HFFFF 'Don't calculate the CRC. 
            CH = (C And &HFF00) >> 8
            Buf(j) = CH
            CL = (C And &HFF)
            Buf(j + 1) = CL
            mTCPClient.SendData(Buf)
        Else
            OnLog("Can't send message. Sos phone not connected")
        End If
    End Sub
 
#End Region
 
#Region "SOS phone --> Central message processing"
 
    Private Sub ParseMessage(ByVal Message As Byte(), ByVal Length As Integer)
        'Parses the incoming message from the sos phone and acts accordingly
        Dim Number As Byte
        Dim Command As Byte
        Dim MasterOrSlave As Byte
 
        Number = Message(0) 'Not used
        Command = Message(1)
        If UBound(Message) > 1 Then MasterOrSlave = Message(2)
 
        Select Case Command 'See the file "message definitions.vb" for help
            Case DEM_USE : Process_DEM_USE(MasterOrSlave)
            Case DEM_SER : Process_DEM_SER(MasterOrSlave)
            Case ENV_ALA : Process_ENV_ALA(Message(2), Message(3))
 
            Case ACK_VOZ_ON : Process_ACK_VOZ_ON(MasterOrSlave, Message(3))
            Case ACK_VOZ_OFF : Process_ACK_VOZ_OFF(MasterOrSlave)
            Case ACK_TON_ON : Process_ACK_TON_ON(MasterOrSlave)
            Case ACK_TON_OFF : Process_ACK_TON_OFF(MasterOrSlave)
            Case ACK_FON_ON : Process_ACK_FON_ON(MasterOrSlave)
            Case ACK_FON_OFF : Process_ACK_FON_OFF(MasterOrSlave, Message(3))
            Case ACK_ESC_IO : Process_ACK_ESC_IO()
            Case ACK_LEC_IO : Process_ACK_LEC_IO(Message(3))
            Case ACK_ADJ_VOL : Process_ACK_ADJ_VOL(Message(3))
            Case RES_TST_MAN : Process_RES_TST_MAN(Message(2), Message(3), Message(6), Message(7))
            Case RES_TST_FON : Process_RES_TST_FON(MasterOrSlave, Message(3))
            Case ACK_ECO_ON : Process_ACK_ECO_ON()
            Case ACK_ECO_OFF : Process_ACK_ECO_OFF()
            Case ACK_ADJ_MIC : Process_ACK_ADJ_MIC(Message(3))
        End Select
    End Sub
 
    Private Sub Process_DEM_USE(ByVal MasterOrSlave As Byte)
        Dim S As String
        mStatus = Status.Received_DEM_USE
        SendMessage(ACK_DEM_USE, MasterOrSlave, 0)
        If MasterOrSlave = P_ESC Then S = "slave" Else S = "master"
        OnLog("User call from " + S + " phone")
        OnIncomingUserCall(MasterOrSlave)
    End Sub
 
    Private Sub Process_DEM_SER(ByVal MasterOrSlave As Byte)
        Dim S As String
        mStatus = Status.Received_DEM_SER
        SendMessage(ACK_DEM_SER, MasterOrSlave, 0)
        If MasterOrSlave = P_ESC Then S = "slave" Else S = "master"
        OnLog("Service call from " + S + " phone")
        OnIncomingServiceCall(MasterOrSlave)
    End Sub
 
    Private Sub Process_ENV_ALA(ByVal AL_M As Byte, ByVal AL_E As Byte)
        SendMessage(ACK_ENV_ALA, 255)
        OnLog("Alarms received")
        mMasterPhoneSatatus = AL_M
        mSlavePhoneStatus = AL_E
        mUpdatedAlarms = False 'True
        OnAlarmsReceived()
    End Sub
 
    Private Sub Process_ACK_FON_ON(ByVal MasterOrSlave As Byte)
        mStatus = Status.Received_ACK_FON_ON
        OnLog("Received ACK_FON_ON")
        'MsgBox("Received ACK_FON_ON")
    End Sub
 
    Private Sub Process_ACK_FON_OFF(ByVal MasterOrSlave As Byte, ByVal Success As Byte)
        Dim S As String
        mStatus = Status.Received_ACK_FON_OFF
        If Success = FON_OFF_OK Then S = " Audio closed" Else S = " Audio NOT closed"
        OnLog("Received ACK_FON_OFF" + S)
    End Sub
 
    Private Sub Process_ACK_VOZ_ON(ByVal MasterOrSlave As Byte, ByVal TM As Byte)
        mStatus = Status.Received_ACK_VOZ_ON
        OnLog("Received ACK_VOZ_ON")
    End Sub
 
    Private Sub Process_ACK_VOZ_OFF(ByVal MasterOrSlave As Byte)
        mStatus = Status.Received_ACK_VOZ_OFF
        OnLog("Received ACK_FON_OFF")
    End Sub
 
    Private Sub Process_ACK_TON_ON(ByVal MasterOrSlave As Byte)
        mStatus = Status.Received_ACK_TON_ON
        OnLog("Received ACK_TON_ON")
    End Sub
 
    Private Sub Process_ACK_TON_OFF(ByVal MasterOrSlave As Byte)
        mStatus = Status.Received_ACK_TON_OFF
        OnLog("Received ACK_TON_OFF")
    End Sub
 
    Private Sub Process_ACK_ESC_IO()
        mStatus = Status.Received_ACK_ESC_IO
        OnLog("Received ACK_ESC_IO")
    End Sub
 
    Private Sub Process_ACK_LEC_IO(ByVal Inputs As Byte)
        OnLog("Received ACK_LEC_IO")
        mStatus = Status.Received_ACK_LEC_IO
        mAuxiliaryPort = Inputs
        OnAuxiliaryPortRead(Inputs)
    End Sub
 
    Private Sub Process_ACK_ADJ_VOL(ByVal Volume As Byte)
        OnLog("Received ACK_ADJ_VOL")
        mStatus = Status.Received_ACK_ADJ_VOL
    End Sub
 
    Private Sub Process_RES_TST_MAN(ByVal MasterStatus As Byte, ByVal SlaveStatus As Byte, ByVal MasterVolume As Byte, ByVal SlaveVolume As Byte)
        OnLog("Received RES_TST_MAN")
        mStatus = Status.Received_RES_TST_MAN
        mMasterPhoneSatatus = MasterStatus
        mSlavePhoneStatus = SlaveStatus
        mMasterPhoneVolume = MasterVolume
        mSlavePhoneVolume = SlaveVolume
        mUpdatedAlarms = False 'True
        OnMaintenanceTestCompleted()
    End Sub
 
    Private Sub Process_RES_TST_FON(ByVal MasterOrSlave As Byte, ByVal Result As Byte)
        OnLog("Received RES_TST_FON")
        mStatus = Status.Received_RES_TST_FON
        mAudioTestResult = Result
        OnAudioTestCompleted(Result)
    End Sub
 
    Private Sub Process_ACK_ECO_ON()
        mStatus = Status.Received_ACK_ECO_ON
        OnLog("Received ACK_ECO_ON")
    End Sub
 
    Private Sub Process_ACK_ECO_OFF()
        mStatus = Status.Received_ACK_ECO_OFF
        OnLog("Received ACK_ECO_OFF")
    End Sub
 
    Private Sub Process_ACK_ADJ_MIC(ByVal Volume As Byte)
        mStatus = Status.Received_ACK_ADJ_MIC
        OnLog("Received ACK_ADJ_MIC")
    End Sub
 
#End Region
 
#Region "Central --> Sos phone message processing"
 
    Public Sub AudioMessageOn(ByVal Type As AudioMessageType, ByVal MasterOrSlave As Byte)
        Dim T As Byte
        If Type = AudioMessageType.OutOfService Then T = MEN_FUE_SER
        If Type = AudioMessageType.ReceivedCall Then T = MEN_LLA_ESP
        If Not MessageSent(ORD_VOZ_ON, MasterOrSlave, T) Then
            OnLog("Audio message on failed!")
        End If
    End Sub
 
    Public Sub AudioMessageOff(ByVal MasterOrSlave As Byte)
        If Not MessageSent(ORD_VOZ_OFF, MasterOrSlave) Then
            OnLog("Audio message off failed!")
        End If
    End Sub
 
    Public Sub ToneOn(ByVal MasterOrSlave As Byte, ByVal Type As ToneType)
        Dim T As Byte
        If Type = ToneType.Occupied Then T = T_COM
        If Type = ToneType.Ringing Then T = T_LLA
        If Not MessageSent(ORD_TON_ON, MasterOrSlave, T) Then
            OnLog("ToneOn failed!")
        End If
    End Sub
 
    Public Sub ToneOff(ByVal MasterOrSlave As Byte)
        If Not MessageSent(ORD_TON_OFF, MasterOrSlave) Then
            OnLog("ToneOff failed!")
        End If
    End Sub
 
    Public Sub AudioOn(ByVal MasterOrSlave As Byte)
        Dim mRTPDestinationIP(3) As Byte
        Dim mRTPDestinationPort_H As Byte
        Dim mRTPDestinationPort_L As Byte
        Dim ComputerIP As System.Net.IPAddress
 
        Dim i As Integer
 
        For i = 1 To System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList.Length
            ComputerIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(i - 1)
            If ((ComputerIP.ToString.Contains("172.16.")) Or (ComputerIP.ToString.Contains("192.168."))) Then
                i = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList.Length + 10
            End If
        Next i
 
        mRTPDestinationIP = ComputerIP.GetAddressBytes()
        mRTPDestinationPort_H = &H55
        mRTPDestinationPort_L = &H55
 
        If MessageSent(ORD_FON_ON, MasterOrSlave, mRTPDestinationIP(0), mRTPDestinationIP(1), mRTPDestinationIP(2), mRTPDestinationIP(3), mRTPDestinationPort_L, mRTPDestinationPort_H) Then
            mStatus = Status.AudioOn
            ReactivationTimer.Configure(ORD_FON_ON, MasterOrSlave, mRTPDestinationIP(0), mRTPDestinationIP(1), mRTPDestinationIP(2), mRTPDestinationIP(3), mRTPDestinationPort_H, mRTPDestinationPort_L)
            ReactivationTimer.TxtLog = "Audio reactivation"
            ReactivationTimer.Start()
            'AudioWindow.SetBounds(0, 0, 0, 0)
            'AudioWindow.SetDesktopBounds(0, 0, 0, 0)
            AudioWindow.SetDesktopLocation(373, 86)
 
            AudioWindow.Show()
            'AudioWindow.Hide()
            'AudioWindow.Text = "Audio communication with sos Phone " + Format(mNumber, "000") + " [" + mDescription + "]"
            AudioWindow.AudioStart(mIp, mRTPPort, &H5555, MasterOrSlave)
        Else
            OnLog("AudioOn Failed!")
        End If
    End Sub
 
    Public Sub AudioOn(ByVal MasterOrSlave As Byte, ByVal windowName As String)
        Dim mRTPDestinationIP(3) As Byte
        Dim mRTPDestinationPort_H As Byte
        Dim mRTPDestinationPort_L As Byte
        Dim ComputerIP As System.Net.IPAddress
 
        Dim i As Integer
 
        For i = 1 To System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList.Length
            ComputerIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(i - 1)
            If ((ComputerIP.ToString.Contains("172.16.")) Or (ComputerIP.ToString.Contains("192.168."))) Then
                i = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList.Length + 10
            End If
        Next i
 
        mRTPDestinationIP = ComputerIP.GetAddressBytes()
        mRTPDestinationPort_H = &H55
        mRTPDestinationPort_L = &H55
 
        If MessageSent(ORD_FON_ON, MasterOrSlave, mRTPDestinationIP(0), mRTPDestinationIP(1), mRTPDestinationIP(2), mRTPDestinationIP(3), mRTPDestinationPort_L, mRTPDestinationPort_H) Then
            mStatus = Status.AudioOn
            ReactivationTimer.Configure(ORD_FON_ON, MasterOrSlave, mRTPDestinationIP(0), mRTPDestinationIP(1), mRTPDestinationIP(2), mRTPDestinationIP(3), mRTPDestinationPort_H, mRTPDestinationPort_L)
            ReactivationTimer.TxtLog = "Audio reactivation"
            ReactivationTimer.Start()
            'AudioWindow.SetBounds(0, 0, 0, 0)
            'AudioWindow.SetDesktopBounds(0, 0, 0, 0)
            AudioWindow.SetDesktopLocation(387, 82)
 
            AudioWindow.Show()
            'AudioWindow.Hide()
            AudioWindow.Text = windowName
            '"Audio communication with sos Phone " + Format(mNumber, "000") + " [" + mDescription + "]"
            AudioWindow.AudioStart(mIp, mRTPPort, &H5555, MasterOrSlave)
        Else
            OnLog("AudioOn Failed!")
        End If
    End Sub
 
    Public Sub AudioOff(ByVal MasterOrSlave As Byte)
        AudioWindow.AudioStop()
        AudioWindow.Hide()
        ReactivationTimer.Stop()
        If Not MessageSent(ORD_FON_OFF, MasterOrSlave) Then
            OnLog("AudioOff failed!")
        End If
    End Sub
 
    Public Sub MaitenanceTest()
        If Not MessageSent(ORD_TST_MAN, 255) Then
            OnLog("MaitenanceTest failed!")
        End If
    End Sub
 
    Public Sub AudioTest(ByVal MasterOrSlave As Byte)
        If Not MessageSent(ORD_TST_FON, MasterOrSlave) Then
            OnLog("Audio Test failed!")
        End If
    End Sub
 
    Public Sub WriteAuxiliaryPort(ByVal Data As Byte)
        If Not MessageSent(ORD_ESC_IO, 0, Data) Then
            OnLog("Write to Auxiliary Port failed")
        End If
    End Sub
 
    Public Sub ReadAuxiliaryPort()
        If Not MessageSent(ORD_LEC_IO, 0) Then
            OnLog("Read from auxilary port failed")
        End If
    End Sub
 
    Public Sub ChangeOutputVolume(ByVal MasterOrSlave As Byte, ByVal Volume As Byte)
        If Not MessageSent(ORD_ADJ_VOL, MasterOrSlave, Volume) Then
            OnLog("Cahnge output volume failed!")
        End If
    End Sub
 
    Public Sub EchoCancellerOn()
        If Not MessageSent(ORD_ECO_ON, 0) Then
            OnLog("Echo canceller on failed!")
        End If
    End Sub
 
    Public Sub EchoCancellerOff()
        If Not MessageSent(ORD_ECO_OFF, 0) Then
            OnLog("Echo canceller off failed")
        End If
    End Sub
 
    Public Sub ChangeMicVolume(ByVal MasterOrSlave As Byte, ByVal Volume As Byte)
        If Not MessageSent(ORD_ADJ_MIC, MasterOrSlave, Volume) Then
            OnLog("Change mic volume failed!")
        End If
    End Sub
 
    Private Function MessageSent(ByVal Command As Byte, ByVal MasterOrSlave As Byte, _
                                          ByVal ParamArray Data() As Byte) As Boolean
        Dim Attempts As Byte
        Dim NextStatus As Status
        Dim Received As Boolean
        Dim TxtCommand As String = ""
        Dim TxtACK As String = ""
        Dim TStart As Long
 
        Select Case Command
            Case ORD_FON_OFF
                mStatus = Status.Sent_ORD_FON_OFF
                NextStatus = Status.Received_ACK_FON_OFF
                TxtCommand = "ORD_FON_OFF"
                TxtACK = "ACK_FON_OFF"
            Case ORD_FON_ON
                mStatus = Status.Sent_ORD_FON_ON
                NextStatus = Status.Received_ACK_FON_ON
                TxtCommand = "ORD_FON_ON"
                TxtACK = "ACK_FON_ON"
            Case ORD_TON_OFF
                mStatus = Status.Sent_ORD_TON_OFF
                NextStatus = Status.Received_ACK_TON_OFF
                TxtCommand = "ORD_TON_OFF"
                TxtACK = "ACK_tON_OFF"
            Case ORD_TON_ON
                mStatus = Status.Sent_ORD_TON_ON
                NextStatus = Status.Received_ACK_TON_ON
                TxtCommand = "ORD_TON_ON"
                TxtACK = "ACK_TON_ON"
            Case ORD_TST_FON
                mStatus = Status.Sent_ORD_TST_FON
                NextStatus = Status.Received_RES_TST_FON
                TxtCommand = "ORD_TST_FON"
                TxtACK = "RES_TST_FON"
            Case ORD_VOZ_OFF
                mStatus = Status.Sent_ORD_VOZ_OFF
                NextStatus = Status.Received_ACK_VOZ_OFF
                TxtCommand = "ORD_VOZ_OFF"
                TxtACK = "ACK_VOZ_OFF"
            Case ORD_VOZ_ON
                mStatus = Status.Sent_ORD_VOZ_ON
                NextStatus = Status.Received_ACK_VOZ_ON
                TxtCommand = "ORD_VOZ_ON"
                TxtACK = "ACK_VOZ_ON"
            Case ORD_ADJ_VOL
                mStatus = Status.Sent_ORD_ADJ_VOL
                NextStatus = Status.Received_ACK_ADJ_VOL
                TxtCommand = "ORD_ADJ_VOL"
                TxtACK = "ACK_ADJ_VOL"
            Case ORD_ESC_IO
                mStatus = Status.Sent_ORD_ESC_IO
                NextStatus = Status.Received_ACK_ESC_IO
                TxtCommand = "ORD_ESC_IO"
                TxtACK = "ACK_ESC_IO"
            Case ORD_LEC_IO
                mStatus = Status.Sent_ORD_LEC_IO
                NextStatus = Status.Received_ACK_LEC_IO
                TxtCommand = "ORD_LEC_IO"
                TxtACK = "ACK_LEC_IO"
            Case ORD_TST_MAN
                mStatus = Status.Sent_ORD_TST_MAN
                NextStatus = Status.Received_RES_TST_MAN
                TxtCommand = "ORD_TST_MAN"
                TxtACK = "RES_TST_MAN"
            Case ORD_ECO_ON
                mStatus = Status.Sent_ORD_ECO_ON
                NextStatus = Status.Received_ACK_ECO_ON
                TxtCommand = "ORD_ECO_ON"
                TxtACK = "ACK_ECO_ON"
            Case ORD_ECO_OFF
                mStatus = Status.Sent_ORD_ECO_OFF
                NextStatus = Status.Received_ACK_ECO_OFF
                TxtCommand = "ORD_ECO_OFF"
                TxtACK = "ACK_ECO_OFF"
            Case ORD_ADJ_MIC
                mStatus = Status.Sent_ORD_ADJ_MIC
                NextStatus = Status.Received_ACK_ADJ_MIC
                TxtCommand = "ORD_ADJ_MIC"
                TxtACK = "ACK_ADJ_MIC"
        End Select
 
        Received = False
        For Attempts = 1 To MaxtemptsNumer
            SendMessage(Command, MasterOrSlave, Data)
            OnLog("Sent " + TxtCommand)
            TStart = DateAndTime.Timer
            While ((DateAndTime.Timer - TStart) < mAttemptsTime) And Not Received
                If mStatus = NextStatus Then
                    Received = True
                End If
                Application.DoEvents()
            End While
            If Received Then
                Exit For
            Else
                OnLog("Timeout waiting " + TxtACK)
            End If
        Next
        If Not Received Then
            OnLog("No response to " + TxtCommand + " after " + MaxtemptsNumer.ToString + " attepmpts.")
        End If
        Return Received
    End Function
#End Region
 
#Region "Event trapp"
    Private Sub ReactivationTimer_Elapsed(ByVal Sender As Object, ByVal E As System.Timers.ElapsedEventArgs) Handles ReactivationTimer.Elapsed
        'We must re-send the command to keep the audio on...
        Dim T As ClassReactivationTimer
        Dim Est As Status
 
        T = Sender
        Est = mStatus
        OnLog(T.TxtLog)
        If MessageSent(T.mCommand, T.mMasterOrSlave, T.mData) Then
            'Return the status to the last one...
            mStatus = Est
        End If
    End Sub
 
    Private Sub AudioWindow_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles AudioWindow.FormClosing
        'If the Audio window closes, we must send the audio off command to the sos phone
        AudioOff(AudioWindow.MasterOrSlave)
        AudioWindow.AudioStop()
        AudioWindow.Hide()
        e.Cancel = True
    End Sub
 
    Private Sub AudioWindow_Log(ByVal Text As String) Handles AudioWindow.Log
        OnLog(Text)
    End Sub
#End Region
 
#Region "Auxilary functions"
 
    Private Function CRC(ByVal Datagram() As Byte, ByVal Size As Byte) As UShort
        Dim Reg As UShort
        Dim Acc As UShort
        Dim Tmp As UShort
        Dim i, j As Integer
 
        For i = 0 To Size - 1
            Reg = Datagram(i)
            Reg = Reg << 8
            For j = 0 To 7
                Tmp = Reg Xor Acc
                Acc = Acc << 1
                If (Tmp And &H8000) = &H8000 Then
                    Acc = Acc Xor &H1021
                End If
                Reg = Reg << 1
            Next
        Next
        Return Acc
    End Function
#End Region
 
#End Region
 
End Class