SafeDispatch/Safedispatch_4_0/maptab/Radio/RadioTab.cs
2024-02-22 18:43:59 +02:00

5695 lines
257 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using System.Threading;
using Telerik.WinControls.Data;
using System.Runtime.InteropServices;
using SafeMobileLib;
using System.Collections;
using System.IO;
using NAudio.CoreAudioApi;
using Dispatcher.maptab.UIClasses;
using System.Globalization;
using NAudio.Wave;
using System.Diagnostics;
namespace Safedispatch_4_0.Radio
{
public partial class RadioTab : UserControl
{
private MainForm2 parent;
private BindingList<Recording> recordingsList = new BindingList<Recording>();
private List<Subscriber> subscribersList = new List<Subscriber>();
public TcpClass tcpAudio;
private Size normalSizeAudioSettings;
private Size normalSizeChannelSettings;
private DBrecordingsManager db;
public SMdb_access smdbObj = null;
public MainForm2 mainparent;
public volatile Boolean RecivedData = false;
private Hashtable AllCallHT = new Hashtable();
private Hashtable rgwHTByName = new Hashtable();
private Dictionary<string, bool> PriorityEmergency = new Dictionary<string, bool>();
DBgatewaysManager DBgw;
private DBcallPatchManager dbpatch = new DBcallPatchManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
private Telerik.WinControls.UI.RadDesktopAlert RemoteMonitorDesktopAlert;
List<Patch> dbPatches;
private SafeMobileLib.Recording toAddRecording = null;
[DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
List<User> dispatchers = new List<User>();
List<RadioGateway> radiogateways = new List<RadioGateway>();
List<string> patchList = new List<string>();
Dictionary<string, List<string>> patchDictionary = new Dictionary<string, List<string>>();
List<String> runningPatches = new List<string>();
public static int voicemanager_sampleRate = 8000;
public static int voicemanager_bufferMilliseconds = 32;
public static int voicemanager_bitDepth = 16;
public RadioTab(MainForm2 parent)
{
InitializeComponent();
mainparent = parent;
pbPTT.BackColor = Color.Transparent;
pbPTT.Parent = pbSpectrum;
pbPTT.Location = new Point(8, 8);
this.parent = parent;
panelInterConnect.ControlsContainer.PanelContainer.BorderStyle = BorderStyle.None;
panelInterConnect.ControlsContainer.PanelElement.Border.Visibility = ElementVisibility.Collapsed;
panelAudioSettings.ControlsContainer.PanelContainer.BorderStyle = BorderStyle.None;
panelAudioSettings.ControlsContainer.PanelElement.Border.Visibility = ElementVisibility.Collapsed;
panelChannelSettings.ControlsContainer.PanelContainer.BorderStyle = BorderStyle.None;
panelChannelSettings.ControlsContainer.PanelElement.Border.Visibility = ElementVisibility.Collapsed;
panelCallHistory.ControlsContainer.PanelContainer.BorderStyle = BorderStyle.None;
panelCallHistory.ControlsContainer.PanelElement.Border.Visibility = ElementVisibility.Collapsed;
panelSettings.Collapse();
#region THEMING
/*
btPrintReport.ButtonElement.ButtonFillElement.BackColor = MainForm2.ButtonColor;
labelReportName.ForeColor = MainForm2.LabelColor;
rgbReport.GroupBoxElement.Header.Border.TopColor = MainForm2.ButtonColor;
rgbReport.GroupBoxElement.Header.Border.TopShadowColor = MainForm2.ButtonColor;
rgbReport.GroupBoxElement.Header.TextPrimitive.ForeColor = MainForm2.ButtonColor;*/
pbPlayTestSound.Image = themePlay_Image;
pb24H.Image = theme24H_Image;
btRecordingsList_EnabledChanged(btRecordingsList, null);
if (MainForm2.radioType == RADIOTYPE.REPEATER_TRBO)
{
// flag that recordings layout should be for repeater
RecordingGridCellElement.REPEATER_LAYOUT = true;
radPanel3.Visible = false;
radPanel5.Visible = false;
rcbBubble.Visible = false;
panelCallHistory.Invalidate();
panelCallHistory.Refresh();
panelCallHistory.Location = new Point(0, 0);
radPanel6.Location = new Point(radPanel6.Location.X, 0);
radPanel4.Size = this.Size;
radPanel4.Dock = DockStyle.Fill;
radPanel4.BringToFront();
panelCallHistory.Size = this.Size;
panelCallHistory.Dock = DockStyle.Fill;
}
#endregion
// create the toolTip that will be displayed when the user sets a pattern
// over the hint pictureBox
toolTipHelp = new ToolTip();
toolTipHelp.ToolTipTitle = "Live";
toolTipHelp.AutoPopDelay = 0;
toolTipHelp.InitialDelay = 0;
toolTipHelp.ReshowDelay = 0;
toolTipHelp.IsBalloon = false;
toolTipHelp.ShowAlways = true;
//load all the gateways for our user
LoadAllGateways();
//init all multicast listener
StartVoiceMulticast(MainForm2.radioType);
#region RECORDINGS LIST
db = new DBrecordingsManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
RecordingGridColumn ctc = new RecordingGridColumn("recording");
ctc.AllowResize = true;
ctc.AllowGroup = true;
ctc.Name = "recording";
ctc.FieldName = "recording";
ctc.HeaderText = "recording";
ctc.AutoSizeMode = BestFitColumnMode.AllCells;
ctc.HeaderTextAlignment = ContentAlignment.MiddleLeft;
ctc.SortOrder = RadSortOrder.Ascending;
this.gridRecordings.TableElement.RowHeight = 59;
this.gridRecordings.Columns.Add(ctc);
this.gridRecordings.Columns.Move(ctc.Index, 0);
this.gridRecordings.GridViewElement.DrawBorder = false;
this.gridRecordings.GridViewElement.GroupPanelElement.DrawBorder = false;
rdpStartTime.Value = DateTime.Now.Date;
rdpEndTime.Value = DateTime.Now.Date.AddDays(1);
// set time grouping
pbFilter_Click(pbFilterTime, null);
#endregion
#region SUBSCRIBERS LIST
listViewSubscribers.ItemSize = new Size(180, 140);
listViewSubscribers.ItemSpacing = 5;
listViewSubscribers.AllowArbitraryItemHeight = false;
listViewSubscribers.AllowArbitraryItemWidth = false;
listViewSubscribers.AllowColumnReorder = false;
listViewSubscribers.AllowEdit = false;
listViewSubscribers.AllowRemove = false;
listViewSubscribers.EnableFiltering = true;
// Populate_subscriber_list();
//listSubscribers.DataSource = subscribersList;
//listSubscribers.DisplayMember = "DispatcherName";
//listSubscribers.EnableCustomGrouping = true;
listViewSubscribers.EnableGrouping = true;
listViewSubscribers.ShowGroups = true;
ListViewDataItemGroup docGroup = new ListViewDataItemGroup("Offline");
ListViewDataItemGroup diskGroup = new ListViewDataItemGroup("Online");
listViewSubscribers.Groups.Add(docGroup);
listViewSubscribers.Groups.Add(diskGroup);
/*
foreach(ListViewDataItem item in listSubscribers.Items)
{
if ((item.DataBoundItem as Subscriber).Offline)
item.Group = docGroup;
else
item.Group = diskGroup;
}*/
// ORDER OF THE GROUPS STARTING WITH ALL AND ENDING WITH SUBSCRIBERS
ListSortDirection sortDirection = String.Compare("Online", "Offline") <= 0 ? ListSortDirection.Descending : ListSortDirection.Ascending;
GroupDescriptor groupByValue = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor("SubscriberTypeRegion", sortDirection) });
listViewSubscribers.GroupDescriptors.Add(groupByValue);
//foreach(ListViewDataItemGroup group in listSubscribers.Groups)
{
}
#endregion
#region FAVORITES LIST
listFavorites.ItemSize = new Size(180, 140);
listFavorites.ItemSpacing = 5;
listFavorites.AllowArbitraryItemHeight = false;
listFavorites.AllowArbitraryItemWidth = false;
listFavorites.AllowColumnReorder = false;
listFavorites.AllowEdit = false;
listFavorites.AllowRemove = false;
listFavorites.EnableFiltering = true;
((IconListViewElement)this.listFavorites.ListViewElement.ViewElement).Orientation = Orientation.Horizontal;
//listFavorites.DataSource = subscribersList;
//listSubscribers.DisplayMember = "DispatcherName";
//listSubscribers.EnableCustomGrouping = true;
listFavorites.EnableGrouping = false;
listFavorites.ShowGroups = false;
FilterDescriptor valueFilter = new FilterDescriptor("Favorite", FilterOperator.IsEqualTo, (Boolean)true);
listFavorites.FilterDescriptors.Clear();
listFavorites.FilterDescriptors.Add(valueFilter);
#endregion
#region GATEWAY LIST
rlvGatewayStatus.ItemSize = new Size(100, 90);
rlvGatewayStatus.ItemSpacing = 5;
rlvGatewayStatus.AllowArbitraryItemHeight = false;
rlvGatewayStatus.AllowArbitraryItemWidth = false;
rlvGatewayStatus.AllowColumnReorder = false;
rlvGatewayStatus.AllowEdit = false;
rlvGatewayStatus.AllowRemove = false;
((IconListViewElement)this.rlvGatewayStatus.ListViewElement.ViewElement).Orientation = Orientation.Horizontal;
rlvGatewayStatus.EnableGrouping = false;
rlvGatewayStatus.ShowGroups = false;
#endregion
#region InitComunication
try
{
smdbObj = new SMdb_access();
ArrayList tmpSound = smdbObj.GetSoundCards(0);
if (tmpSound.Count > 0)
{
selectedOUTDeviceName = tmpSound[0].ToString();
selectedINDeviceName = tmpSound[1].ToString();
//if (tmpSound.Count > 2)
// MainForm2.KeyforPTTall = tmpSound[2].ToString();
//else
// MainForm2.KeyforPTTall = "";
}
else
{
selectedOUTDeviceName = "";
selectedINDeviceName = "";
}
}
catch (Exception ex)
{
SM.Debug("Unable to load sound settings." + ex.ToString());
}
// create the TCP for Audio voice received from mbus
InitListToPlay();
//iniVoiceComponents();
InitAudioInputDevices();
InitAudioOutputDevices();
StartnVoice();
/*udp4Voice2 = new UdpMulticast(voiceMulticastIP2, Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port));
udp4Voice2.OnNewDataRecv += new UdpMulticast.newData4Send(udp4Voice2_OnNewDataRecv);
udp4Voice2.StartListen();*/
//MainForm2.tcpforClose = tcp;
//MainForm2.tcpAudioforClose = tcpAudio;
MainForm2.VoiceTabStarted = true;
CheckMessage.RunWorkerAsync();
#endregion
SetLanguages();
listBoxRadioGateways.DataSource = MainForm2.myGatewaylist;
listBoxRadioGateways.DisplayMember = "DisplayedMemeber";
DBgw.gelAllGatewaysAndRadioGatewaysHT(ref MainForm2.radioGwHT);
rgwHTByName = DBgw.gelAllGatewaysAndRadioGatewaysHTByName();
timer1.Start();
List<RadioGateway> rgw = MainForm2.myGatewaylist.ToList();
rgw.Add(new RadioGateway() { Gw_id = 0, Id = 0, Name = MainForm2.returnLNGString("Unassigned") });
rcbddGateways.DataSource = rgw; //MainForm2.myGatewaylist;
rcbddGateways.DisplayMember = "Name";
rcddlRecordingsGateways.DataSource = rgw; //MainForm2.myGatewaylist;
rcddlRecordingsGateways.DisplayMember = "Name";
#region Sip
AttachEventHandlers();
parent.SipClassInitialized += SipClassInititializedInMainForm;
#endregion
this.parent.OnRadioGatewayStatusChanged += parent_OnRadioGatewayStatusChanged;
this.parent.OnCallStatusHangChanged += parent_OnCallStatusHangChanged;
panelCallHistory.Visible = pbFilterTime.Visible = pbFilterType.Visible = pbFilterUser.Visible = pbFilterDirection.Visible = MainForm2.recordingsDecide;
}
#region Sip Class Event Handlers
private void SipClassInititializedInMainForm(object sender, EventArgs e)
{
AttachEventHandlers();
}
private void AttachEventHandlers()
{
parent.AddDialogCreatedEventHandler(SipDialogCreated);
if (MainForm2.recordingsDecide)
{
parent.AddVoiceReceivedEventHandler(SipVoiceReceived_Recordings);
}
else
parent.AddVoiceReceivedEventHandler(SipVoiceReceived);
parent.AddDialogClosedEventHandler(SipDialogClosed);
parent.AddHangtimeEventHandler(SipHangtime);
parent.AddErrorOnCreatingDialogEventHandler(SipErrorOnCreatingDialog);
parent.AddSdCannotSendVoiceEventArgs(SdCannotSendSipVoice);
parent.AddSdCanSendSipVoiceEventHandler(SdCanSendSipVoice);
parent.AddSdReceivesSipCallInintEventHandler(SdReceivesSipCallInit);
}
private void SipDialogCreated(object sender, Dispatcher.Sip.SipDialogCreatedEventArgs e)
{
// Just show a message
string dialogType = e.GroupId.HasValue ? "Group dialog with " + e.GroupId.Value : "Private dialog";
Utils.WriteLine($"{dialogType} created; {e.SipIdWhoSentInvite} sent the invite to {e.SipIdWhoReceivedInvite}");
}
private void SipVoiceReceived(object sender, Dispatcher.Sip.SipVoiceReceivedEventArgs e)
{
// put the voice on audio output
if (buffWaveProvider != null)
{
string audioSourceSipID = e.GroupId != null ? e.GroupId : e.CallSourceId.ToString();
int audioSourceSipID_int = int.Parse(audioSourceSipID);
int audioSourceRadioID = parent.ContactLinxFromSipID(audioSourceSipID_int)?.Id ?? audioSourceSipID_int;
if (MainForm2.PriorityIP == audioSourceRadioID.ToString())
{
try
{
buffWaveProvider.AddSamples(e.Buffer, 0, e.Buffer.Length);
}
catch(Exception ex)
{
Utils.WriteLine(ex.Message, ConsoleColor.Red);
}
}
}
}
private void SipVoiceReceived_Recordings(object sender, Dispatcher.Sip.SipVoiceReceivedEventArgs e)
{
SipVoiceReceived(null, e);
// There is a licence for recordings
// I will also put the voice on mBus
parent.UdpMultForGwRecording.Send(e.Buffer, e.Buffer.Length);
}
private void SipDialogClosed(object sender, Dispatcher.Sip.SipDialogClosedEventArgs e)
{
string callType = e.GroupId == null ? "Private sip dialog" : "Group sip dialog";
Utils.WriteLine($"{callType} with {e.SipIdInDialogWith} was closed by {e.SipIdWhoClosed}");
if (PTTinprogres // SD sends voice
&& (e.SipIdWhoClosed == e.SipIdInDialogWith) // and SD receives Bye from a unit
&& (e.SipIdWhoClosed == selected_Subscriber.SipID) // and the unit that sends bye is the one that SD has called (in selectedSubscriber?)
)
{
// I received deKey from Linx
killPTT = true;
PTTinprogres = false;
pttIsPressed = false;
RecivedData = MainForm2.PriorityIP != "";
Thread.Sleep(60);
pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_00;
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt;
spectrumCount = 0;
this.Invoke((Action)(() => {
ManageSafeDispatchRingingSound(false);
}));
}
else
{
// Here I will Simulate call end
SimulateCallEnded(
parent.ContactLinxFromSipID(e.SipIdInDialogWith)?.Id.ToString() ?? e.SipIdInDialogWith.ToString(),
e.GroupId != null ? parent.ContactLinxFromSipID(int.Parse(e.GroupId))?.Id.ToString() ?? e.GroupId : MainForm2.userIDX.ToString(),
e.GroupId != null ? SafeMobileLib.CallType.GROUPCALL : SafeMobileLib.CallType.PRIVATECALL,
parent.ContactLinxFromSipID(e.SipIdInDialogWith)?.Type ?? ContactType.UNIT);
}
}
private void SipHangtime(object sender, Dispatcher.Sip.SdReceivedCallStatusEventArgs e)
{
string sourceCallRadioId = parent.ContactLinxFromSipID(e.SourceCallSipId)?.Id.ToString() ?? e.SourceCallSipId.ToString();
string targetCallId = e.GroupCall ?
parent.ContactLinxFromSipID(e.GroupSipId.Value)?.Id.ToString() ?? e.GroupSipId.Value.ToString()
: MainForm2.userIDX.ToString();
// Here I will Simulate hangtime
if (MainForm2.recordingsDecide)
{
// Send 125 with 2
int groupCallType = e.GroupCall ? 103 : 102;
// send 125 on mbus
// I changed the length of the command by adding a last "parameter": #0#
// Sd will not process this longer command, only AppServer will do it for recordings
string toSend = $"#0.0#125#{parent.SipGWIDandRadioID}.{sourceCallRadioId}#2#{groupCallType}#{targetCallId}#0#";
parent.Send_UDP_cmd_sent_withOutID(toSend);
}
SimulateHangtime(
sourceCallRadioId,
targetCallId,
e.GroupCall ? SafeMobileLib.CallType.GROUPCALL : SafeMobileLib.CallType.PRIVATECALL,
parent.ContactLinxFromSipID(e.SourceCallSipId)?.Type ?? ContactType.UNIT);
}
private void SipErrorOnCreatingDialog(object sender, SipComponent.ErrorEventArgs e)
{
// Show error
Utils.WriteLine($"Error on Invite from {e.FromID} to {e.ToID}; Reason: {e.Reason}", ConsoleColor.Red);
}
private void SdReceivesSipCallInit(object sender, Dispatcher.Sip.SdReceivedCallStatusEventArgs e)
{
string sourceCallRadioId = parent.ContactLinxFromSipID(e.SourceCallSipId)?.Id.ToString() ?? e.SourceCallSipId.ToString();
string targetCallId = e.GroupCall ?
parent.ContactLinxFromSipID(e.GroupSipId.Value)?.Id.ToString() ?? e.GroupSipId.Value.ToString()
: MainForm2.userIDX.ToString();
if (MainForm2.recordingsDecide)
{
int groupCallType = e.GroupCall ? 103 : 102;
// send 125 on mbus
string toSend = $"#0.0#125#{parent.SipGWIDandRadioID}.{sourceCallRadioId}#1#{groupCallType}#{targetCallId}#0#";
parent.Send_UDP_cmd_sent_withOutID(toSend);
}
SimulateCallInitiated(
sourceCallRadioId,
targetCallId,
e.GroupCall ?
SafeMobileLib.CallType.GROUPCALL
: SafeMobileLib.CallType.PRIVATECALL,
parent.ContactLinxFromSipID(e.SourceCallSipId)?.Type ?? ContactType.UNIT);
}
private void SdCanSendSipVoice(object sender, Dispatcher.Sip.SdCanSendVoiceEventArgs e)
{
// Stop the ringing
this.Invoke((Action)(() => { ManageSafeDispatchRingingSound(true); }));
// SafeDispatch can now send voice
SDcanSendVoice(e.TargetSipId, e.GroupCall);
}
private void SdCannotSendSipVoice(object sender, Dispatcher.Sip.SdCannotSendVoiceEventArgs e)
{
// Show console info
Utils.WriteLine($"Cannot send ptt to {e.TargetSipId} because {e.Reason}", ConsoleColor.DarkRed);
// Stop the ringing
this.Invoke((Action)(() => { ManageSafeDispatchRingingSound(false); }));
// Check if the failed attempt was private or group call
ContactType linxType = parent.ContactLinxFromSipID(e.TargetSipId)?.Type ?? ContactType.UNIT;
if (linxType == ContactType.GROUP)
{
// Do here what I do when receiving 123 with 2;
Handle123Command(this.IdVOL = 2);
// Show event on System log
// If target sip id is 16777215, then it's an all call
int mBusCmd = e.TargetSipId == 16777215 ? 121 : 123;
// #seqID#123#gatewayId.gatewayRadioId#result#dispatcherID#
string cmd = "";
Utils.Convert_text_For_multicast(
$"#1234#{mBusCmd}#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#2#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
else
{
// Do here what I do when receiving 122 with 2;
Handle122Command(this.IdVOL = 2);
// trigger event for the map
parent.RaiseOnCallStatusChangedEvent(
parent.ContactLinxFromSipID(e.TargetSipId)?.Name ?? "",
false,
false);
// Show event on System log
// #seqID#122#gatewayId.gatewayRadioId#result#dispatcherID#
string cmd = "";
Utils.Convert_text_For_multicast(
$"#1234#122#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#2#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
}
#endregion
#region Private methods for Sip
private void SDcanSendVoice(int targetSipID, bool groupCall)
{
string cmd = "";
if (groupCall)
{
// SD can send voice for sip group call
// If group id is 16777215, then it's an all call
int mbusCmd = targetSipID == 16777215 ? 121 : 123;
if (!MainForm2.recordingsDecide)
{
// Do here what I do when receiving 123 with 1;
Handle123Command(this.IdVOL = 1);
// Show event on System log
// #seqID#123#gatewayId.gatewayRadioId#result#dispatcherID#
Utils.Convert_text_For_multicast(
$"#1234#{mbusCmd}#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#1#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
else
{
// Send 123 with 1 on Mbus, so that AppServer will record
string seqId = parent.GetCallRequestForSip(targetSipID);
if (seqId != null)
{
cmd = $"#{seqId}#{mbusCmd}#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#1#{MainForm2.userIDX}#";
parent.Send_UDP_cmd_sent_withOutID(cmd);
}
}
}
else
{
// SD can send voice for sip private call
if (!MainForm2.recordingsDecide)
{
// Do here what I do when receiving 122 with 1;
Handle122Command(this.IdVOL = 1);
// Trigger event for the map
parent.RaiseOnCallStatusChangedEvent(
parent.ContactLinxFromSipID(targetSipID)?.Name, true, false);
// Show event on System log
// #seqID#122#gatewayId.gatewayRadioId#result#dispatcherID#
Utils.Convert_text_For_multicast(
$"#1234#122#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#1#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
else
{
// Send 122 with 1 on Mbus, so that AppServer will record
string seqId = parent.GetCallRequestForSip(targetSipID);
if (seqId != null)
{
cmd = $"#{seqId}#122#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#1#{MainForm2.userIDX}#";
parent.Send_UDP_cmd_sent_withOutID(cmd);
}
}
}
}
private void SimulateCallInitiated(string sourceCallSipID, string targetCallSipID, SafeMobileLib.CallType callType, ContactType sourceType)
{
string gwID = parent.SipGWIDandRadioID.Split('.')[0];
string radioGwID = parent.SipGWIDandRadioID.Split('.')[1];
parent.Handle125Command(gwID, radioGwID, sourceCallSipID, 1, (int)callType, int.Parse(targetCallSipID), true);
// Add info in system tab
//#0.0#125#gatewayId.gatewayRadioId.sourceRadioId#callStatus# callType#targetId#
string cmd = "";
Utils.Convert_text_For_multicast($"#0.0#125#{gwID}.{radioGwID}.{sourceCallSipID}#1#{(int)callType}#{targetCallSipID}#", out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd, sourceType); }));
// Show call window
this.Invoke((Action)(() =>
{
Handle125Command(gwID, radioGwID,
callStatusVOL = 1,
callTypeVOL = (int)callType,
grpIDVOL = callType == SafeMobileLib.CallType.PRIVATECALL ? MainForm2.userIDX : int.Parse(targetCallSipID),
int.Parse(sourceCallSipID),
sourceType);
}));
}
private void SimulateHangtime(string sourceCallSipID, string targetCallSipID, SafeMobileLib.CallType typeOfCall, ContactType sourceCallType)
{
string gwID = parent.SipGWIDandRadioID.Split('.')[0];
string radioGwID = parent.SipGWIDandRadioID.Split('.')[1];
parent.Handle125Command(gwID, radioGwID, sourceCallSipID, 2, (int)typeOfCall, int.Parse(targetCallSipID), true);
// Show info in System Tab
// Add info in system tab
//#0.0#125#gatewayId.gatewayRadioId.sourceRadioId#callStatus# callType#targetId#
string cmd = "";
Utils.Convert_text_For_multicast($"#0.0#125#{gwID}.{radioGwID}.{sourceCallSipID}#2#{(int)typeOfCall}#{targetCallSipID}#", out cmd);
this.Invoke((Action)(() => {
Handle125Command(gwID, radioGwID, callStatusVOL = 2, callTypeVOL = (int)typeOfCall, grpIDVOL = MainForm2.userIDX, int.Parse(sourceCallSipID));
parent.AddDataToSystemGrid(false, cmd, sourceCallType);
}));
}
private void SimulateCallEnded(string sourceCallSipID, string targetCallSipID, SafeMobileLib.CallType typeOfCall, ContactType sourceCallType)
{
string gwID = parent.SipGWIDandRadioID.Split('.')[0];
string radioGwID = parent.SipGWIDandRadioID.Split('.')[1];
parent.Handle125Command(gwID, radioGwID, sourceCallSipID, 3, (int)typeOfCall, int.Parse(targetCallSipID), true);
// Show info in System Tab
// Add info in system tab
//#0.0#125#gatewayId.gatewayRadioId.sourceRadioId#callStatus# callType#targetId#
string cmd = "";
Utils.Convert_text_For_multicast($"#0.0#125#{gwID}.{radioGwID}.{sourceCallSipID}#3#{(int)typeOfCall}#{targetCallSipID}#", out cmd);
this.Invoke((Action)(() => {
Handle125Command(gwID, radioGwID,
callStatusVOL = 3,
callTypeVOL = (int)typeOfCall,
grpIDVOL = (typeOfCall == SafeMobileLib.CallType.PRIVATECALL ? MainForm2.userIDX : int.Parse(targetCallSipID)),
int.Parse(sourceCallSipID));
parent.AddDataToSystemGrid(false, cmd, sourceCallType);
}));
}
internal void UpdateSipStatus(bool status)
{
this.Invoke((MethodInvoker)delegate ()
{
try
{
lbSipStatus.Text = (status ? MainForm2.returnLNGString("sipConnected") : MainForm2.returnLNGString("sipNotConnected")) + $"[{MainForm2.userSipId}]";
lbSipStatus.ForeColor = status ? Color.Green : Color.Red;
}
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
});
}
private void CloseSipCall(string callerName)
{
// Dekey for linx call
if (MainForm2.vehicleHT.ContainsKey(callerName))
{
// id is from an unit.
// Close the call
parent.StopPtt(((Vehicle)MainForm2.vehicleHT[callerName]).sipID.ToString());
}
else if (MainForm2.userIDHash.ContainsKey(callerName))
{
// id is from a dispatcher.
// get the sip id.
User dispatcher = MainForm2.UsersList.FirstOrDefault((user) => { return user.UserName == callerName; });
if (dispatcher != null)
parent.StopPtt(dispatcher.SipID.ToString());
}
}
#endregion
private void SetLanguages()
{
radLabel1.Text = MainForm2.returnLNGString("call");
rlPushToTalk.Text = MainForm2.returnLNGString("PushtoTalk");
panelCallHistory.Text = MainForm2.returnLNGString("callHistory");
tbSearch.NullText = MainForm2.returnLNGString("search");
rcpFavoritesPanel.HeaderText = MainForm2.returnLNGString("favSubscribers");
rcbCallType.NullText = rcbUnit.NullText = MainForm2.returnLNGString("displayall");
radLabel10.Text = MainForm2.returnLNGString("calltype");
radLabel11.Text = MainForm2.returnLNGString("htableVehiclesListColumns1");
rlRecordingsFrom.Text = MainForm2.returnLNGString("recordingsFrom");
rlRecordingsUntil.Text = MainForm2.returnLNGString("recordingsUntil");
btRecordingsList.Text = MainForm2.returnLNGString("exportRecordingsList");
rcbBubble.Text = MainForm2.returnLNGString("displayBubble");
panelAudioSettings.Text = MainForm2.returnLNGString("audioSett");
rlMicrophone.Text = MainForm2.returnLNGString("microphone");
rlSpeakers.Text = MainForm2.returnLNGString("speakers");
rbApplyAudioConfiguration.Text = MainForm2.returnLNGString("ApplyConfig");
panelChannelSettings.HeaderText = MainForm2.returnLNGString("RadioChannelSettings");
radLabel7.Text = MainForm2.returnLNGString("radio");
radLabel5.Text = MainForm2.returnLNGString("zonex");
radLabel6.Text = MainForm2.returnLNGString("chanel");
panelInterConnect.HeaderText = MainForm2.returnLNGString("InterConnectedSubscribers");
panelCallHistory.HeaderText = MainForm2.returnLNGString("callHistory");
panelSettings.HeaderText = MainForm2.returnLNGString("sett");
panelAudioSettings.HeaderText = MainForm2.returnLNGString("audioSett");
lbGatewayStatus.Text = MainForm2.returnLNGString("gwStatus");
rddFieldFilter.Items.Add(MainForm2.returnLNGString("htableVehiclesListColumns1"));
rddFieldFilter.Items.Add(MainForm2.returnLNGString("imei"));
rddFieldFilter.SelectedIndex = 0;
rcbddGateways.NullText = MainForm2.returnLNGString("displayAllGateways");
rcddlRecordingsGateways.NullText = MainForm2.returnLNGString("displayAllGateways");
lblPatch.Text = MainForm2.returnLNGString("callPatching");
rlVolumeIndicator.Text = rlVolumeIndicator2.Text = MainForm2.returnLNGString("volumeIndicator");
rlMicrophone.Text = MainForm2.returnLNGString("microphone");
rlSpeakers.Text = MainForm2.returnLNGString("speakers");
rlVoiceStatus.Text = MainForm2.returnLNGString("voiceStatusPerGw");
gvPatch.Columns[0].HeaderText = MainForm2.returnLNGString("type");
gvPatch.Columns[1].HeaderText = MainForm2.returnLNGString("incomingFrom");
gvPatch.Columns[2].HeaderText = MainForm2.returnLNGString("redirectTo");
}
/// <summary>
/// Get the volume for the default audio device
/// </summary>
private void UpdateVolume()
{
/*
// By the default set the volume to 0
uint CurrVol = 0;
// At this point, CurrVol gets assigned the volume
waveOutGetVolume(IntPtr.Zero, out CurrVol);
// Calculate the volume
ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
// Get the volume on a scale of 1 to 10 (to fit the trackbar)
rtbSpeakersVolume.Value = CalcVol / (ushort.MaxValue / 10);*/
}
private List<Subscriber> Populate_subscriber_list()
{
try
{
subscribersList.Clear();
#region SUBSCRIBERS
foreach (String obj in MainForm2.vehicleHT.Keys)
{
if (((Vehicle)MainForm2.vehicleHT[obj]).GwandRadioID.Equals("-1.-1"))
((Vehicle)MainForm2.vehicleHT[obj]).GwandRadioID = "0.0";
RadioGateway rg = MainForm2.myGatewaylist.Find(d => ((Vehicle)MainForm2.vehicleHT[obj]).GwandRadioID.Equals(d.Gw_id + "." + d.Id));
if (obj.Equals("655"))
;
//((Vehicle)MainForm2.vehicleHT[obj]).CheckPositionInSystem();
subscribersList.Add(new Subscriber()
{
DispatcherName = obj,
SubscriberType = SubscriberType.SUBSCRIBER,
SubscriberTypeRegion = MainForm2.returnLNGString(SubscriberType.SUBSCRIBER.ToString()),
ImageKey = "i_classic_bus_02",
HasRemoteMonitor = (MainForm2.radioType == RADIOTYPE.MOTO ? true : false),
HasTextMessage = true,
Sc_id = ((Vehicle)MainForm2.vehicleHT[obj]).sc_id,
Imei = ((Vehicle)MainForm2.vehicleHT[obj]).IMEI,
IconFilePath = MainForm2.GetMapPathForUnit(obj),
//Gw_and_radioID = Valid_GwID_and_RadioID,
Gw_and_radioID = (rg?.Name == null ? "0.0" : ((Vehicle)MainForm2.vehicleHT[obj]).GwandRadioID),
GatewayName = rg?.Name ?? MainForm2.returnLNGString("Unassigned"),
IP = String.Format("224.10.{0}", ((Vehicle)MainForm2.vehicleHT[obj]).GwandRadioID),
//IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
Favorite = ((Vehicle)MainForm2.vehicleHT[obj]).is_favorite,
IsEmergency = ((Vehicle)MainForm2.vehicleHT[obj]).is_emergency,
canMakeSipCalls = ((Vehicle)MainForm2.vehicleHT[obj]).canMakeSipCalls,
SipID = ((Vehicle)MainForm2.vehicleHT[obj]).sipID
});
}
subscribersList.Sort((x, y) => x.DispatcherName.CompareTo(y.DispatcherName));
#endregion
#region GROUP
//Group g = null;
foreach (var g in MainForm2.GroupCPSIDOnlyHashWithoutCategory)
{
//g = (Group)MainForm2.GroupCPSIDOnlyHashWithoutCategory[i];
string hashKey = "isFav" + "_" + SubscriberType.GROUP.ToString() + "_"
+ g.Value.Id.ToString() + g.Value.Gw_and_radioID;
bool isFav = MainForm2.HashVal.ContainsKey(hashKey) ? Boolean.Parse(MainForm2.HashVal[hashKey] + "") : false;
try
{
RadioGateway rg = MainForm2.myGatewaylist.Find(d => g.Value.Gw_and_radioID.Equals(d.Gw_id + "." + d.Id));
// skip groups that are assignet to other radio gateways
if (rg == null)
continue;
subscribersList.Add(new Subscriber()
{
DispatcherName = g.Value.Name,
SubscriberType = SubscriberType.GROUP,
SubscriberTypeRegion = MainForm2.returnLNGString(SubscriberType.GROUP.ToString()),
HasRemoteMonitor = false,
HasTextMessage = (MainForm2.radioType == RADIOTYPE.MOTO ? true : false),
ImageKey = "i_group",
IconFilePath = "i_group",
Imei = g.Value.Id.ToString(),
GatewayName = rg?.Name??"",
//Gw_and_radioID = Valid_GwID_and_RadioID,
Gw_and_radioID = g.Value.Gw_and_radioID,
IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
Favorite = isFav,
canMakeSipCalls = g.Value.Type == (int)GatewayType.Broadband || MainForm2.radioType == RADIOTYPE.EXCERA,
SipID = g.Value.SipID,
Id = g.Value.Id
});
}
catch (Exception ex)
{
Utils.WriteLine("Unable to create Group: " + ex.ToString(), ConsoleColor.Red);
}
}
#endregion
#region DISPATCHER
//Dispatcher to dispatcher call needs to be added before uncomenting
//foreach (var user in MainForm2.UsersList.OrderBy(d => d.UserName))
//{
// if (user.Id != MainForm2.userIDX)
// {
// string hashKey3 = "isFav" + "_" + SubscriberType.DISPATCHER.ToString() + "_"
// + user.Id.ToString() + "_" + user.UserName;
// bool isFav3 = MainForm2.HashVal.ContainsKey(hashKey3) ? Boolean.Parse(MainForm2.HashVal[hashKey3] + "") : false;
// subscribersList.Add(new Subscriber()
// {
// DispatcherName = user.UserName,
// SubscriberType = SubscriberType.DISPATCHER,
// SubscriberTypeRegion = MainForm2.returnLNGString(SubscriberType.DISPATCHER.ToString()),
// HasRemoteMonitor = false,
// HasTextMessage = false,
// Gw_and_radioID = "0.0",
// GatewayName = MainForm2.returnLNGString("Unassigned"),
// ImageKey = "i_dispatch",
// IconFilePath = "i_dispatch",
// IP = String.Format("224.20.{0}.1", MainForm2.userIDX.ToString()),
// Imei = user.Id.ToString(),
// Favorite = isFav3,
// canMakeSipCalls = false
// });
// }
//}
#endregion
#region ALL CALL
if (MainForm2.radioType == RADIOTYPE.MOTO)
{
foreach (RadioGateway radgw in MainForm2.myGatewaylist.OrderBy(d => d.Name))
{
string hashKey2 = "isFav" + "_" + SubscriberType.ALL.ToString() + "_" + "16777215" + "_" +
radgw.Name;
bool isFav2 = MainForm2.HashVal.ContainsKey(hashKey2) ? Boolean.Parse(MainForm2.HashVal[hashKey2] + "") : false;
subscribersList.Add(new Subscriber()
{
DispatcherName = radgw.Name,
SubscriberType = SubscriberType.ALL,
SubscriberTypeRegion = MainForm2.returnLNGString(SubscriberType.ALL.ToString()),
HasRemoteMonitor = false,
HasTextMessage = false,
Imei = "16777215",
SipID = 16777215,
ImageKey = "i_all_call",
IconFilePath = "i_all_call",
GatewayName = radgw.Name,
//Gw_and_radioID = Valid_GwID_and_RadioID,
Gw_and_radioID = (String)(radgw.Gw_id.ToString() + "." + radgw.Id.ToString()),
//IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
IP = String.Format("224.10.{0}", (String)(radgw.Gw_id.ToString() + "." + radgw.Id.ToString())),
Favorite = isFav2,
canMakeSipCalls = radgw.Type == (int)GatewayType.Broadband || MainForm2.radioType == RADIOTYPE.EXCERA
});
if (!AllCallHT.ContainsKey(radgw.Name))
AllCallHT.Add(radgw.Name, (String)(radgw.Gw_id.ToString() + "." + radgw.Id.ToString()));
}
}
#endregion
//subscribersList = subscribersList.OrderBy(d => d.DispatcherName).ToList();
listViewSubscribers.DataSource = subscribersList;
listFavorites.DataSource = null;
listFavorites.DataSource = subscribersList;
if (this.listViewSubscribers.Items.Count > 0)
{
ListViewDataItem item = null;
foreach(ListViewDataItemGroup g in listViewSubscribers.Groups)
{
if (g.Text.StartsWith(SubscriberType.ALL.ToString()))
{
item = g.Items[0];
break;
}
}
if(item!= null)
{
selected_Subscriber = (Subscriber)item.DataBoundItem;
listViewSubscribers.Select(new ListViewDataItem[] { item });
listViewSubscribers.ListViewElement.ViewElement.Scroller.ScrollToItem(item);
Update_call_selected();
}
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on Populate subscriber list:" + ex.ToString(), ConsoleColor.Red);
}
return subscribersList;
}
public String Valid_GwID_and_RadioID = "";
public static string responseGW = "";
public static volatile string PersonalIP = "";
public String Valid_GwID = "0";
private void Populate_recording_list()
{
try
{
List<SafeMobileLib.Recording> recList = new List<SafeMobileLib.Recording>();
ArrayList param = new ArrayList();
// 0 typesd 0 =gateway 1 = dispather
// 1 gw_id
// 2 radiogw_id //sc_id from the field in case o dispatcher
// 3 subscriber_id // user_id of dispatcher
// User type
param.Add(1);
// User type gateway ID 0
param.Add(Convert.ToInt32(Valid_GwID));
// User type radio gateway ID 0
param.Add(0);
// User type my user id
param.Add(MainForm2.userIDX);
foreach (RadioGateway obj in MainForm2.myGatewaylist)
{
param.Add(0);
param.Add((Int32)obj.Gw_id);//1
param.Add((Int32)obj.Id);//8
param.Add(0); // i don't limit to specify subscriber
}
string from = "", to = "";
recList = db.GetAllRecordingsForDispatcherAndAssignGateway(param, 0, Int32.MaxValue, MainForm2.userIDX);
int i = 0;
foreach (SafeMobileLib.Recording obj in recList)
{
if (i++ == 0)
{
toAddRecording = obj;
toAddRecording.startDateTime = DateTime.Now;
toAddRecording.endDateTime = DateTime.Now.AddSeconds(7);
}
//obj.calltype
//obj.startTime and obj.endTime
//obj.startDateTime
//obj.id for PLAY
//obj.hddLocation for info
//obj.typeSD and obj.subID and obj.Group_ID
CallDirection calldir = CallDirection.INCOMING;
if (obj.calltype < 4) calldir = CallDirection.OUTGOING;
if (obj.calltype == 3)
{
calldir = obj.dispatcher_id == MainForm2.userIDX ? CallDirection.OUTGOING : CallDirection.INCOMING;
}
CallType callty = CallType.REMOTE_MONITORING;
String Name = "";
CheckRecording(obj, out callty, out Name, out from, out to);
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (obj.gwID + "." + obj.radioGWID).Equals(d.Gw_id + "." + d.Id));
// do not display recordings from radio gateways that are not assigned anymore or where deleted
if (rg == null)
continue;
recordingsList.Add(new Recording()
{
callDirection = calldir,
callType = callty,
dateUnix70 = obj.startTime,
duration = (int)(obj.endTime - obj.startTime),
username = Name,
To = to,
From = from,
File_Name = obj.hddLocation,
RecID = obj.id,
Gw_and_radioID = (rg?.Name == null ? "0.0" : obj.gwID + "." + obj.radioGWID),
GatewayName = rg?.Name??"N/A [deleted]"
});
}
Thread.Sleep(100);
gridRecordings.DataSource = recordingsList;
// set the time to be first recordings time and today
rdpStartTime.Value = recordingsList.Count > 0 ? recordingsList[recordingsList.Count - 1].DateStart : DateTime.Now.Date;
rdpEndTime.Value = DateTime.Now.Date.AddDays(1);
DisplayEmptyMessageOnRecordingsGrid();
}
catch (Exception ex)
{
Utils.WriteLine("Error on populate recordings:" + ex.ToString(), ConsoleColor.Red);
}
}
private List<Gateway> listgw = new List<Gateway>();
private void LoadAllGateways()
{
try
{
DBgw = new DBgatewaysManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
listgw = DBgw.getAllGateways();
foreach (Gateway rad in listgw)
{
List<RadioGateway> listRadgw = DBgw.gelAllRadioGateways_forUser(rad.Id, MainForm2.userIDX);
foreach (RadioGateway radgw in listRadgw)
{
if (radgw.Gw_voice == 1)
{
//MainForm2.myGatewaylist.Add(radgw);
Valid_GwID_and_RadioID = (String)(rad.Id.ToString() + "." + radgw.Id);
Valid_GwID = rad.Id.ToString();
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on load gateway: " + ex.ToString(), ConsoleColor.Red);
}
}
public void StartVoiceMulticast(RADIOTYPE radioType)
{
//UdpMulticast udp4Voice2;
Gatewaymulticast gatewaymulticast;
if (radioType != RADIOTYPE.EXCERA)
{
// for Excera, the dispatcher should not lister for voice from gateways
foreach (RadioGateway radgw in MainForm2.myGatewaylist)
{
Valid_GwID_and_RadioID = (String)(radgw.Gw_id.ToString() + "." + radgw.Id.ToString());
//udp4Voice2 = new UdpMulticast(String.Format("224.10.{0}", Valid_GwID_and_RadioID), Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port));
//udp4Voice2.OnNewDataRecv += new UdpMulticast.newData4Send(udp4Voice2_OnNewDataRecv);
//udp4Voice2.StartListen();
gatewaymulticast = new Gatewaymulticast(String.Format("224.10.{0}", Valid_GwID_and_RadioID), Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port), this);
Console.WriteLine("Listen to:" + String.Format("224.10.{0}", Valid_GwID_and_RadioID));
//List_of_multicast_voice.Add(udp4Voice2);
}
}
foreach (Int32 obj in MainForm2.userIDHash.Keys)
{
if (obj != MainForm2.userIDX)
{
//udp4Voice2 = new UdpMulticast(String.Format("224.20.{0}.1", obj.ToString()), Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port));
//udp4Voice2.OnNewDataRecv += new UdpMulticast.newData4Send(udp4Voice2_OnNewDataRecv);
//udp4Voice2.StartListen();
gatewaymulticast = new Gatewaymulticast(String.Format("224.20.{0}.1", obj.ToString()), Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port), this);
Console.WriteLine("Listen to:" + String.Format("224.20.{0}.1", obj.ToString()));
//List_of_multicast_voice.Add(udp4Voice2);
}
}
}
/// <summary>
/// Add the new recording row to the recordings grid
/// </summary>
/// <param name="obj">New recording object</param>
public void Addrow(SafeMobileLib.Recording obj)
{
try
{
CallDirection calldir = CallDirection.INCOMING;
if (obj.calltype < 4) calldir = CallDirection.OUTGOING;
CallType callty = CallType.REMOTE_MONITORING;
if(obj.calltype == 3)
{
calldir = obj.dispatcher_id == MainForm2.userIDX ? CallDirection.OUTGOING : CallDirection.INCOMING;
}
String Name = "", to = "", from = "";
CheckRecording(obj, out callty, out Name, out from, out to);
//gridRecordings.BeginUpdate();
this.Invoke((MethodInvoker)delegate ()
{
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (obj.gwID + "." + obj.radioGWID).Equals(d.Gw_id + "." + d.Id));
// add the new row to the list
//Utils.WriteLine("Add recording: " + obj.gwID, ConsoleColor.Red);
recordingsList.Insert(0, new Recording()
{
callDirection = calldir,
callType = callty,
dateUnix70 = obj.startTime,
duration = (int)(obj.endTime - obj.startTime),
username = Name,
File_Name = obj.hddLocation,
RecID = obj.id,
Gw_and_radioID = (rg?.Name == null ? "0.0" : obj.gwID + "." + obj.radioGWID),
GatewayName = rg?.Name ?? "",
To = to,
From = from
});
});
//gridRecordings.EndUpdate();
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
}
private void CheckRecording(SafeMobileLib.Recording obj, out CallType callType, out string nameOfTheRecording, out string userWhoCalled,
out string userWhoWasCalled)
{
callType = CallType.REMOTE_MONITORING;
nameOfTheRecording = userWhoWasCalled = userWhoCalled = "";
switch (obj.calltype)
{
case 0:
callType = CallType.PRIVATE_CALL;
userWhoCalled = MainForm2.userLog;
if (MainForm2.VehIMEIHash.ContainsKey(obj.subs_imei.ToString()))
{
userWhoWasCalled = (String)MainForm2.VehIMEIHash[obj.subs_imei.ToString()];
}
else
{
userWhoWasCalled = obj.subs_imei.ToString();
}
break;
case 4:
callType = CallType.PRIVATE_CALL;
userWhoWasCalled = MainForm2.userLog;
if (MainForm2.VehIMEIHash.ContainsKey(obj.subs_imei.ToString()))
{
userWhoCalled = (String)MainForm2.VehIMEIHash[obj.subs_imei.ToString()];
}
else
{
userWhoCalled = obj.subs_imei.ToString();
}
break;
case 1:
callType = CallType.GROUP_CALL;
userWhoCalled = MainForm2.userLog;
string key = obj.group_cpsId + "." + obj.radioGWID;
if (MainForm2.GroupsAndRadioGW.ContainsKey(key))
userWhoWasCalled = ((Group)MainForm2.GroupsAndRadioGW[key]).Name;
else
userWhoWasCalled = obj.group_cpsId.ToString();
break;
case 5:
callType = CallType.GROUP_CALL;
if (MainForm2.VehIMEIHash.ContainsKey(obj.subs_imei.ToString()))
userWhoCalled = (String)MainForm2.VehIMEIHash[obj.subs_imei.ToString()];
else
userWhoCalled = obj.subs_imei.ToString();
//"recordings/Tetra102(102)_DO_GROUP_CALL_ID_457_02_Jul_19_13_16_20.wav"
string key1 = obj.group_cpsId + "." + obj.radioGWID;
string GroupIDFromPath="";
string[] GroupIDFromSplit;
if (MainForm2.GroupsAndRadioGW.ContainsKey(key1))
userWhoWasCalled = ((Group)MainForm2.GroupsAndRadioGW[key1]).Name;
else
{
if (obj.group_cpsId == null)
{
GroupIDFromPath = obj.hddLocation;
GroupIDFromSplit = GroupIDFromPath.Split('_');
userWhoWasCalled = GroupIDFromSplit[5];
}
else
userWhoWasCalled = obj.group_cpsId.ToString();
}
break;
case 2:
callType = CallType.ALL_CALL;
userWhoCalled = MainForm2.userLog;
userWhoWasCalled = "All Call";
break;
case 6:
callType = CallType.ALL_CALL;
userWhoWasCalled = "All Call";
if (MainForm2.VehIMEIHash.ContainsKey(obj.subs_imei.ToString()))
userWhoCalled = (String)MainForm2.VehIMEIHash[obj.subs_imei.ToString()];
else
userWhoCalled = obj.subs_imei.ToString();
break;
case 7:
callType = CallType.REMOTE_MONITORING;
userWhoWasCalled = MainForm2.userLog;
if (MainForm2.VehIMEIHash.ContainsKey(obj.subs_imei.ToString()))
userWhoCalled = (String)MainForm2.VehIMEIHash[obj.subs_imei.ToString()];
else
userWhoCalled = "Radio_ID " + obj.subs_imei;
break;
case 3:
callType = CallType.DISPATCHER_CALL;
//userWhoCalled = MainForm2.userLog;
userWhoCalled = MainForm2.userIDHash[obj.dispatcher_id] != null ? (string)MainForm2.userIDHash[obj.dispatcher_id] : "UserID" + obj.dispatcher_id;
if (MainForm2.userIDHash.ContainsKey(obj.radioGWID))
userWhoWasCalled = (String)MainForm2.userIDHash[obj.radioGWID];
else
userWhoWasCalled = "UserID" + obj.radioGWID;
break;
}
nameOfTheRecording = userWhoCalled + " -> " + userWhoWasCalled;
}
private void radTrackBar1_LabelFormatting(object sender, Telerik.WinControls.UI.LabelFormattingEventArgs e)
{
try
{
if (e.LabelElement == null)
return;
if (e.LabelElement.Text == null)
e.LabelElement.Text = "";
//make the top labels display the days
if (e.LabelElement.Text.Equals("0") && !e.LabelElement.Text.Equals("100"))
{
e.LabelElement.Text = MainForm2.returnLNGString("Low");
}
if (e.LabelElement.Text.Equals("100") && !e.LabelElement.Text.Equals("0"))
{
e.LabelElement.Text = MainForm2.returnLNGString("High");
}
else if (!e.LabelElement.Text.Equals(MainForm2.returnLNGString("Low")) && !e.LabelElement.Text.Equals(MainForm2.returnLNGString("High")))
{
e.LabelElement.Text = "";
}
}
catch(Exception ex)
{
Utils.WriteLine("Error when setting volume trackbar labels" + ex.ToString());
}
}
private void tbSearch_TextChanged(object sender, EventArgs e)
{
if (tbSearch.Text.Length == 0)
{
pbSearch.Image = Dispatcher.Properties.Resources.i_search;
pbSearch.Cursor = Cursors.Default;
}
else
{
pbSearch.Image = Dispatcher.Properties.Resources.i_delete;
pbSearch.Cursor = Cursors.Hand;
}
FilterDescriptor valueFilter = null;
listViewSubscribers.BeginUpdate();
listViewSubscribers.FilterDescriptors.Remove("DispatcherName");
listViewSubscribers.FilterDescriptors.Remove("Imei");
valueFilter = rddFieldFilter.SelectedIndex == 0 ?
new FilterDescriptor("DispatcherName", FilterOperator.Contains, tbSearch.Text)
: new FilterDescriptor("Imei", FilterOperator.Contains, tbSearch.Text);
listViewSubscribers.FilterDescriptors.Add(valueFilter);
/*
listSubscribers.FilterDescriptors.Remove("DispatcherName");
FilterDescriptor valueFilter = new FilterDescriptor("DispatcherName", FilterOperator.Contains, tbSearch.Text);
/*
while (listSubscribers.FilterDescriptors.Count > 0)
listSubscribers.FilterDescriptors.RemoveAt(0);
*/
/*listSubscribers.FilterDescriptors.Add(valueFilter);*/
listViewSubscribers.EndUpdate();
if (this.listViewSubscribers.Items.Count == 1)
{
selected_Subscriber = (Subscriber)listViewSubscribers.Items[0].DataBoundItem;
listViewSubscribers.SelectedIndex = 0;
Update_call_selected();
}
}
private void pbSearch_Click(object sender, EventArgs e)
{
if (tbSearch.Text.Length > 0)
tbSearch.Text = "";
}
private void panel_Collapsed(object sender, EventArgs e)
{
if ((RadCollapsiblePanelElement)sender == panelAudioSettings.CollapsiblePanelElement)
{
panelChannelSettings.Location =
new Point(panelChannelSettings.Location.X,
panelChannelSettings.Location.Y - normalSizeAudioSettings.Height + 33);
panelInterConnect.Location =
new Point(panelInterConnect.Location.X,
panelInterConnect.Location.Y - normalSizeAudioSettings.Height + 33);
dividerChannelSettings.Location = new Point(dividerChannelSettings.Location.X,
dividerChannelSettings.Location.Y - normalSizeAudioSettings.Height + 33);
dividerInterConnect.Location = new Point(dividerInterConnect.Location.X,
dividerInterConnect.Location.Y - normalSizeAudioSettings.Height + 33);
}
else if ((RadCollapsiblePanelElement)sender == panelChannelSettings.CollapsiblePanelElement)
{
panelInterConnect.Location =
new Point(panelInterConnect.Location.X,
panelInterConnect.Location.Y - normalSizeChannelSettings.Height + 33);
dividerInterConnect.Location = new Point(dividerInterConnect.Location.X,
dividerInterConnect.Location.Y - normalSizeChannelSettings.Height + 33);
}
else if ((RadCollapsiblePanelElement)sender == panelInterConnect.CollapsiblePanelElement)
{
}
}
private void panel_Expanding(object sender, CancelEventArgs e)
{
Console.WriteLine("Size is : " + normalSizeChannelSettings.Height);
if ((RadCollapsiblePanelElement)sender == panelAudioSettings.CollapsiblePanelElement)
{
panelChannelSettings.Location =
new Point(panelChannelSettings.Location.X,
panelChannelSettings.Location.Y + normalSizeAudioSettings.Height - 33);
panelInterConnect.Location =
new Point(panelInterConnect.Location.X,
panelInterConnect.Location.Y + normalSizeAudioSettings.Height - 33);
dividerChannelSettings.Location = new Point(dividerChannelSettings.Location.X,
dividerChannelSettings.Location.Y + normalSizeAudioSettings.Height - 33);
dividerInterConnect.Location = new Point(dividerInterConnect.Location.X,
dividerInterConnect.Location.Y + normalSizeAudioSettings.Height - 33);
}
else if ((RadCollapsiblePanelElement)sender == panelChannelSettings.CollapsiblePanelElement)
{
panelInterConnect.Location =
new Point(panelInterConnect.Location.X,
panelInterConnect.Location.Y + normalSizeChannelSettings.Height - 33);
dividerInterConnect.Location = new Point(dividerInterConnect.Location.X,
dividerInterConnect.Location.Y + normalSizeChannelSettings.Height - 33);
}
else if ((RadCollapsiblePanelElement)sender == panelInterConnect.CollapsiblePanelElement)
{
}
}
private void RadioTab_Load(object sender, EventArgs e)
{
normalSizeAudioSettings = panelAudioSettings.CollapsiblePanelElement.Size;
normalSizeChannelSettings = panelChannelSettings.CollapsiblePanelElement.Size;
//get all recordings
LoadRecordingTimer.Enabled = true;
LoadRecordingTimer.Start();
//subscriber list
LoadSubscriberTimer.Enabled = true;
LoadSubscriberTimer.Start();
// fill the recordings list
Populate_recording_list();
// fill the subscribers list
Populate_subscriber_list();
// fill the units combobox
populateUnits();
// fill the call types
rcbCallType.DataSource = new CallTypeBindingList();
rcbCallType.DisplayMember = "Name";
rcbCallType.ValueMember = "Id";
// get first time the volume level
UpdateVolume();
//request
String Totrans = "#503#";
mainparent.Send_UDP_cmd(Totrans, 0, 0);
//display current datetime on watch
lbCurrentDateTime.Text = DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
//SetPTTButtonEnableDisable();
#region grid patching data source
foreach (var user in MainForm2.UsersList)
{
//if (user.UserName != MainForm2.userLog)
dispatchers.Add(user);
}
foreach (var gateway in MainForm2.myGatewaylist.OrderBy(d => d.Name))
{
radiogateways.Add(gateway);
}
List<string> patchType = new List<string>();
if (dispatchers.Count >= 2) patchType.Add("Dispatcher");
if (radiogateways.Count >= 2) patchType.Add("Gateway");
((GridViewComboBoxColumn)gvPatch.Columns["type"]).DataSource = patchType;
//hide patch table if doesn't need it
if (MainForm2.radioType == RADIOTYPE.MOTO)
lblPatch.Visible = gvPatch.Visible = (radiogateways.Count >= 2 || dispatchers.Count >= 2);
else
lblPatch.Visible = gvPatch.Visible = false;
dbPatches = dbpatch.getAllPatches();
gvPatch.DataSource = dbPatches;
//add data into patching dictionary
foreach (var patch in dbPatches)
{
string concat = patch.Type + patch.Incoming + patch.Outgoing;
string key = patch.Type + "." + patch.IncomingId;
//updatePatchStatus(patch.Incoming, true);
updatePatchStatus(patch.Outgoing, true, patch.Type);
if (!patchDictionary.ContainsKey(key))
{
patchDictionary.Add(key, new List<string>());
}
if (patchDictionary.ContainsKey(key))
{
if (!patchDictionary[key].Contains(patch.OutgoingId))
patchDictionary[key].Add(patch.OutgoingId);
}
patchList.Add(concat);
}
#endregion
if (MainForm2.radioType == RADIOTYPE.LINX || MainForm2.radioType == RADIOTYPE.LINXB || MainForm2.radioType == RADIOTYPE.EXCERA)
UpdateSipStatus(MainForm2.sipStatus);
else
lbSipStatus.Text = MainForm2.returnLNGString("gatewayStatus");
//lbSipStatus.Visible = MainForm2.radioType == RADIOTYPE.LINX || MainForm2.radioType == RADIOTYPE.LINXB;
//update224Route(MainForm2.cfg.LocalIP);
rcpFavoritesPanel.Collapse();
// hide radio gateway status list and panel because no active gateway assigned to the dispatcher
if (radiogateways.Count == 0)
containerGatewayStatus.Visible = false;
else
{
// set datasource for gateway status list
rlvGatewayStatus.DataSource = radiogateways;
rlvGatewayStatus.DisplayMember = "DisplayedMemeber";
rlvGatewayStatus.EnableFiltering = true;
// add filter to show only voice gateways
rlvGatewayStatus.BeginUpdate();
rlvGatewayStatus.FilterDescriptors.Add(new FilterDescriptor("Gw_voice", FilterOperator.IsGreaterThan, 0));
rlvGatewayStatus.EndUpdate();
}
}
private void update224Route(string interfaceIP)
{
Process p = new Process();
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = $"/c route change 224.0.0.0 mask 240.0.0.0 {interfaceIP}";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
}
/// <summary>
/// Update the Radio Status list from the Settings tab. The status can be online or offline
///
/// </summary>
/// <param name="gwandradioGW"></param>
/// <param name="status"></param>
void parent_OnRadioGatewayStatusChanged(string gwandradioGW, bool status)
{
foreach (RadListDataItem tmp in listBoxRadioGateways.Items)
{
if (((RadioGateway)tmp.Value).Gw_id.ToString() + "." + ((RadioGateway)tmp.Value).Id.ToString() == gwandradioGW)
{
// update the gateway status to offline or idle when the radio gateway status changes
OnRadioGatewayStateChanged((RadioGateway)MainForm2.radioGwHT[gwandradioGW], status ? RadioState.IDLE : RadioState.OFFLINE);
tmp.Image = status == true ? global::Dispatcher.Properties.Resources.green_status : global::Dispatcher.Properties.Resources.grey_status;
((RadioGateway)MainForm2.radioGwHT[gwandradioGW]).Alive = status;
break;
}
}
this.Invoke((MethodInvoker)delegate
{
if(!pttIsPressed)
SetPTTButtonEnableDisable();
});
}
void parent_OnCallStatusHangChanged(string unitname, bool inCall, Boolean fromField, string GwPlusRadio)
{
//Thread.Sleep(250);
if (MainForm2.radioGwHT.ContainsKey(GwPlusRadio))
{
RadioGateway radioGw = (RadioGateway)MainForm2.radioGwHT[GwPlusRadio];
Utils.WriteLine($"Radiogateway {GwPlusRadio} - {radioGw.Name} Patch status is {radioGw.InPatch}", ConsoleColor.Yellow);
if (radioGw.InPatch)
return;
}
ManageSafeDispatchRingingSound(inCall);
}
/// <summary>
/// Stops the ringing sound when call is established.
/// <para>If not in call, plays busy sound and display error on ptt button</para>
/// <para>Must be called ON THE UI THREAD</para>
/// </summary>
/// <param name="callEstablished">true if in call, otherwise false</param>
private void ManageSafeDispatchRingingSound(bool callEstablished)
{
MainForm2.soundPlayer.Stop();
if (!callEstablished)
{
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
MainForm2.soundPlayer.Stream = Dispatcher.Properties.Resources.phone_busy;
MainForm2.soundPlayer.Play();
}
}
private ArrayList vehicleListNames = new ArrayList();
public BindingList<DropListItem> UnitGroupItems = new BindingList<DropListItem>();
/// <summary>
/// Populate the drop down list with all the units
/// </summary>
private void populateUnits()
{
// add the datasource for the vehicles ComboBox
rcbUnit.DataSource = null;
List<String> unitsName = (subscribersList.Select(x => x.DispatcherName).ToList<String>());
// add dispatcher to the list
unitsName.Add(MainForm2.userLog);
unitsName.Sort();
rcbUnit.DataSource = unitsName;
//cbVehName.DataSource = vehicleListNames;
//cbVehName.DisplayMember = "Name";
if (rcbUnit.Items.Count > 1)
rcbUnit.SelectedIndex = 0;
}
/// <summary>
/// Get the image which needs to be set for a unit/group picture box/ list
/// according to the type of the SafeDispatch
/// </summary>
/// <param name="radioType">Type of the SafeDispatch system [this is equal with the theme]</param>
/// <param name="iconType">String containing the </param>
/// <param name="isEnabled">Specify if the icon should be in enabled or disabled state</param>
/// <returns>The image which fulfills the constrains</returns>
private Image GetIconForCombobox(RADIOTYPE radioType, String iconType, bool isEnabled)
{
if (iconType.Equals("unit"))
{
switch (MainForm2.radioType)
{
case RADIOTYPE.ATLAS:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_unit_enabled : Dispatcher.Properties.Resources.icon_cb_unit_disabled);
case RADIOTYPE.HARRIS:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_unit_enabled_ha : Dispatcher.Properties.Resources.icon_cb_unit_disabled);
default:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_unit_enabled : Dispatcher.Properties.Resources.icon_cb_unit_disabled);
}
}
else if (iconType.Equals("group"))
{
switch (MainForm2.radioType)
{
case RADIOTYPE.ATLAS:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_group_enabled : Dispatcher.Properties.Resources.icon_cb_group_disabled);
case RADIOTYPE.HARRIS:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_group_enabled_ha : Dispatcher.Properties.Resources.icon_cb_group_disabled);
default:
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_group_enabled : Dispatcher.Properties.Resources.icon_cb_group_disabled);
}
}
return (isEnabled ? Dispatcher.Properties.Resources.icon_cb_group_enabled : Dispatcher.Properties.Resources.icon_cb_group_disabled);
}
private void rcbCallType_ItemDataBound(object sender, ListItemDataBoundEventArgs args)
{
var test = args.NewItem.DataBoundItem as CallType_Drop;
if (test == null)
{
return;
}
args.NewItem.Image = test.Image;
}
#region PTT
internal volatile bool pttIsPressed = false;
volatile bool killPTT = false;
int spectrumCount = 0;
internal void pbPTT_MouseDown(object sender, MouseEventArgs e)
{
if (selected_Subscriber == null)
return;
//if (listViewSubscribers.SelectedItem == null && listViewSubscribers.Items.Count > 0)
// //listViewSubscribers.Items[0].Selected = true;
// listViewSubscribers.SelectedItem = listViewSubscribers.Items[0];
//selected_Subscriber = listViewSubscribers.SelectedItem.DataBoundItem as Subscriber;
selected_Subscriber = selected_Subscriber_PTT;
if (selected_Subscriber.SubscriberType == SubscriberType.SUBSCRIBER)
{
if (selected_Subscriber.DispatcherName != "")
{
((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).CheckPositionInSystem();
selected_Subscriber.Gw_and_radioID = Valid_GwID_and_RadioID = ((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).GwandRadioID;
}
}
else if (selected_Subscriber.SubscriberType == SubscriberType.ALL)
{
Valid_GwID_and_RadioID = AllCallHT[selected_Subscriber.DispatcherName].ToString();
}
else if (selected_Subscriber.SubscriberType == SubscriberType.GROUP)
{
Valid_GwID_and_RadioID = selected_Subscriber.Gw_and_radioID;
}
sendPTT(selected_Subscriber);
}
private void sendRemoteMOnitor(Subscriber sel_subs)
{
// pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_over;
String Totrans = "";
if (sel_subs.SubscriberType == SubscriberType.SUBSCRIBER)
{
Totrans = "#161#" + sel_subs.Gw_and_radioID + "." + sel_subs.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 15000, 161));
}
}
private void sendDekey(string linxSipID = null)
{
if (linxSipID != null)
{
int sipID;
if (int.TryParse(linxSipID, out sipID))
{
// close sip call
parent.StopPtt(sipID.ToString());
}
}
else
{
// Send deDekey to radio GW
String Totrans = String.Format("#160#{0}#", responseGW);
mainparent.Send_UDP_cmd(Totrans, 0, 0);
}
}
private void sendCallStop(String Imei)
{
//String Totrans = String.Format("#220#{0}.{1}#", Valid_GwID_and_RadioID, Imei);
String Totrans = String.Format("#220#{0}.{1}#{2}#", responseGW, Imei, MainForm2.userIDX);
mainparent.Send_UDP_cmd(Totrans, 0, 0);
}
public void updateGwAndRagioGatewayForSubscriber(String radioID, String gwId, String radioGwId)
{
//Utils.WriteLine("updateGwAndRagioGatewayForSubscriber " + radioID, ConsoleColor.DarkMagenta);
listViewSubscribers.BeginUpdate();
listViewSubscribers.FilterDescriptors.Remove("GatewayName");
foreach (Object item in subscribersList)
{
Subscriber sub = item as Subscriber;
if (sub == null)
continue;
if (sub.Imei.Equals(radioID))
{
// do not update the dispatcher gateway
if (sub.SubscriberType == SubscriberType.DISPATCHER)
continue;
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (gwId + "." + radioGwId).Equals(d.Gw_id + "." + d.Id));
// update the value of the subscriber in the grid
if (sub.SubscriberType == SubscriberType.SUBSCRIBER)
{
sub.Gw_and_radioID = (rg?.Name == null ? "0.0" : gwId + "." + radioGwId);
sub.GatewayName = rg?.Name ?? MainForm2.returnLNGString("Unassigned");
//Utils.WriteLine("Moved unit " + sub.DispatcherName + " to " + sub.Gw_and_radioID);
sub.NrOfUpdates++;
}
}
}
listViewSubscribers.EndUpdate();
listFavorites.FilterDescriptors.Remove("GatewayName");
listFavorites.BeginUpdate();
foreach (ListViewDataItem item in listFavorites.Items)
{
Subscriber sub = item.DataBoundItem as Subscriber;
if (sub == null)
continue;
if (sub.Imei.Equals(radioID))
{
// do not update the dispatcher gateway
if (sub.SubscriberType == SubscriberType.DISPATCHER)
continue;
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (gwId + "." + radioGwId).Equals(d.Gw_id + "." + d.Id));
// update the value of the subscriber in the grid
if (sub.SubscriberType == SubscriberType.SUBSCRIBER)
{
// update the value of the subscriber in the grid
sub.Gw_and_radioID = (rg?.Name == null ? "0.0" : gwId + "." + radioGwId);
sub.GatewayName = rg?.Name ?? MainForm2.returnLNGString("Unassigned");
sub.NrOfUpdates++;
Utils.WriteLine("Moved unit " + sub.DispatcherName + " to " + sub.Gw_and_radioID);
}
}
}
listFavorites.EndUpdate();
rcbddGateways_ItemCheckedChanged(rcbddGateways, null);
}
public void sendPTT(Subscriber sub, bool selectSubscriberInListView = false)
{
if (PTTinprogres)
{
// PTT already in progress. Just return
return;
}
#region BUG: Voice call fails in various situations
//1. if proces111or112or113FALSE is true means that a mobile radio has a call in progress and if we make a call in this situation
//the call will be intrerupted by it's timer
if (proces111or112or113FALSE)
{
ManageSafeDispatchRingingSound(false);
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
return;
}
#endregion
SubscriberType subType = sub.SubscriberType;
// get the radio gateway
if (subType == SubscriberType.GROUP || subType == SubscriberType.SUBSCRIBER)
{
if (sub.Gw_and_radioID != null)
{
string gwAndRadioGw = sub.Gw_and_radioID;
if (MainForm2.radioGwHT.ContainsKey(gwAndRadioGw))
{
RadioGateway radioGw = (RadioGateway)MainForm2.radioGwHT[gwAndRadioGw];
// Check the radio gateway type
switch (radioGw.Type)
{
case (int)GatewayType.Tier2Radio:
// if gateway is off or already in ptt, do not send ptt
if (!radioGw.Alive || radioGw.InPTT)
{
Utils.WriteLine("PTT is not in progress anymore: " + radioGw.InPTT + " | " + radioGw.Alive);
ManageSafeDispatchRingingSound(false);
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
PTTinprogres = false;
return;
}
break;
case (int)GatewayType.Broadband:
case (int)GatewayType.Tier3Radio:
// Play calling sound for Simoco and android
MainForm2.soundPlayer.Stream = Dispatcher.Properties.Resources.phone_calling;
MainForm2.soundPlayer.Play();
break;
}
}
}
}
killPTT = false;
selected_Subscriber = sub;
if (selected_Subscriber.DispatcherName != "")
{
if (subType == SubscriberType.SUBSCRIBER)
{
((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).CheckPositionInSystem();
selected_Subscriber.Gw_and_radioID = Valid_GwID_and_RadioID = ((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).GwandRadioID;
}
}
if (subType != SubscriberType.DISPATCHER)
selected_Subscriber.Gw_and_radioID = Valid_GwID_and_RadioID;
try
{
String gwId = "0";
String radioGwId = "0";
gwId = Valid_GwID_and_RadioID.Split(new char[] { '.' })[0];
radioGwId = Valid_GwID_and_RadioID.Split(new char[] { '.' })[1];
updateGwAndRagioGatewayForSubscriber(selected_Subscriber.Imei, gwId, radioGwId);
}
catch(Exception ex)
{
Utils.WriteLine("Error on updating the gateway for current selected unit: " + ex.ToString(), ConsoleColor.Red);
}
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_over;
if (selectSubscriberInListView)
{
ListViewDataItem lDataItem = listViewSubscribers.Items.FirstOrDefault((item) =>
{
Subscriber s = item.DataBoundItem as Subscriber;
if (s != null)
{
if (s.Imei == sub.Imei && s.SubscriberType == subType && s.Gw_and_radioID == sub.Gw_and_radioID)
return true;
else return false;
}
else
return false;
});
if (lDataItem != null)
listViewSubscribers.SelectedItem = lDataItem;
}
bool sendCallInitOnMbus = true;
if (selected_Subscriber.canMakeSipCalls)
{
try
{
Utils.WriteLine("SIP ID TO SEND PTT = " + selected_Subscriber.SipID, ConsoleColor.Magenta);
parent.SendCallRequest(selected_Subscriber.SipID.ToString(), selected_Subscriber.SubscriberType == SubscriberType.GROUP ||
selected_Subscriber.SubscriberType == SubscriberType.ALL);
if (!MainForm2.recordingsDecide)
{
// No licence for recordings
// I will not send call init commands on mBus
// I will send them only when there is licence for recordings,
// so that the AppServer will start registering
sendCallInitOnMbus = false;
// Show data in system tab
// init private call - 102
// #seqID#102#gatewayId.gatewayRadioId.remoteRadioId#voiceBroadcastAddress#
// init group call - 103
// #seqID#103#gatewayId.gatewayRadioId.remoteRadioId#voiceBroadcastAddress#
string cmd = "";
MessageBusCmds initCallCmd = MessageBusCmds.InitPrivateCall;
switch (subType)
{
case SubscriberType.GROUP:
initCallCmd = MessageBusCmds.InitGroupCall;
break;
case SubscriberType.ALL:
initCallCmd = MessageBusCmds.InitAllCall;
break;
}
Utils.Convert_text_For_multicast(
$"#1234#{(int)initCallCmd}#{selected_Subscriber.Gw_and_radioID}.{selected_Subscriber.Imei}#224.20.{MainForm2.userIDX}.1#",
out cmd);
parent.AddDataToSystemGrid(true, cmd);
}
}
catch (Exception ex)
{
// Threat this as call rejected by gateway
if (subType == SubscriberType.GROUP)
{
Handle123Command(this.IdVOL = 2);
// Show event on System log
// #seqID#123#gatewayId.gatewayRadioId#result#dispatcherID#
string cmd = "";
Utils.Convert_text_For_multicast(
$"#1234#123#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#2#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
else
{
Handle122Command(this.IdVOL = 2);
// Trigger event for the map
parent.RaiseOnCallStatusChangedEvent(
selected_Subscriber.DispatcherName, false, false);
// Show event on System log
// #seqID#122#gatewayId.gatewayRadioId#result#dispatcherID#
string cmd = "";
Utils.Convert_text_For_multicast(
$"#1234#122#{parent.SipGWIDandRadioID.Split('.')[0]}.{parent.SipGWIDandRadioID.Split('.')[1]}#2#{MainForm2.userIDX}#",
out cmd);
this.Invoke((Action)(() => { parent.AddDataToSystemGrid(false, cmd); }));
}
Utils.WriteLine(ex.Message, ConsoleColor.Red);
}
}
if (sendCallInitOnMbus)
{
String Totrans = "";
string seqId = "";
if (selected_Subscriber != null)
{
switch (subType)
{
case SubscriberType.ALL:
Totrans = String.Format("#101#{0}#{1}#", selected_Subscriber.Gw_and_radioID, "224.20." + MainForm2.userIDX + ".1#0");
WatchList.Add(seqId = mainparent.Send_UDP_cmd(Totrans, 10000, 101));
break;
case SubscriberType.SUBSCRIBER:
Totrans = "#102#" + /*selected_Subscriber.Gw_and_radioID*/ Valid_GwID_and_RadioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
WatchList.Add(seqId = mainparent.Send_UDP_cmd(Totrans, 10000, 102));
break;
case SubscriberType.GROUP:
Totrans = "#103#" + selected_Subscriber.Gw_and_radioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
WatchList.Add(seqId = mainparent.Send_UDP_cmd(Totrans, 10000, 103));
break;
case SubscriberType.DISPATCHER:
Totrans = String.Format("#201#{0}#{1}#", selected_Subscriber.Imei, "224.20." + MainForm2.userIDX + ".1#0");
WatchList.Add(seqId = mainparent.Send_UDP_cmd(Totrans, 10000, 201));
break;
}
#if EXCERA
parent.AddCallRequestForSip(selected_Subscriber.SipID, seqId);
#endif
}
}
}
private void ConfirmPTT_and_Start_Voice()
{
pttIsPressed = true;
try
{
Thread p = new Thread(delegate ()
{
while (pttIsPressed)
{
if (killPTT)
{
Utils.WriteLine("KILL PTTT");
pttIsPressed = false;
//RecivedData = false;
//pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_00;
//pbPTT.Image = Dispatcher.Properties.Resources.r_ptt;
//spectrumCount = 0;
break;
}
//this.Invoke((MethodInvoker)delegate ()
//{
if (pbSpectrum != null)
{
switch (spectrumCount++ % 13)
{
case 1: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_01; break;
case 2: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_02; break;
case 3: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_03; break;
case 4: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_04; break;
case 5: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_05; break;
case 6: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_06; break;
case 7: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_07; break;
case 8: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_08; break;
case 9: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_09; break;
case 10: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_10; break;
case 11: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_11; break;
case 12: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_12; break;
//default: pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_01; break;
}
}
//});
Thread.Sleep(50);
}
});
p.Start();
}
catch (Exception ex)
{
Utils.WriteLine("Error on ConfirmPTT_and_Start_Voice:" + ex.ToString());
}
}
internal void pbPTT_MouseUp(object sender, MouseEventArgs e)
{
Utils.WriteLine("PTT MOUSE UP", ConsoleColor.Green);
if (selected_Subscriber == null)
return;
StopPTT(selected_Subscriber);
}
private void pbPTT_MouseLeave(object sender, EventArgs e)
{
Utils.WriteLine("PTT MOUSE LEAVE", ConsoleColor.Green);
if (PTTinprogres)
{
if (selected_Subscriber == null)
return;
StopPTT(selected_Subscriber);
}
}
public void StopPTT(Subscriber subs)
{
Utils.WriteLine("STOP PTT");
bool sendMbusCommand = true;
if (!PTTinprogres)
sendMbusCommand = false; // PTT is not in progress. No need to do anything
else
killPTT = true; // PTT is in progress, so the animation should be stop
PTTinprogres = false;
MainForm2.soundPlayer.Stop();
selected_Subscriber = subs;
pttIsPressed = false;
//RecivedData = false;
RecivedData = MainForm2.PriorityIP != "";
Thread.Sleep(60);
pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_00;
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt;
spectrumCount = 0;
if (selected_Subscriber.canMakeSipCalls)
{
string sipID = selected_Subscriber.SipID.ToString();
parent.StopPtt(sipID);
sendMbusCommand = MainForm2.recordingsDecide;
}
if (sendMbusCommand)
{
String Totrans = "";
switch (selected_Subscriber.SubscriberType)
{
case SubscriberType.ALL:
Totrans = String.Format("#111#{0}#{1}#", selected_Subscriber.Gw_and_radioID, "224.20." + MainForm2.userIDX + ".1#0");
WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 111));
break;
case SubscriberType.SUBSCRIBER:
Totrans = "#112#" + selected_Subscriber.Gw_and_radioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 112));
if (MainForm2.radioType != RADIOTYPE.EXCERA)
WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 112));
else
mainparent.Send_UDP_cmd(Totrans, 3000, 112);
break;
case SubscriberType.GROUP:
Totrans = "#113#" + selected_Subscriber.Gw_and_radioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 113));
if (MainForm2.radioType != RADIOTYPE.EXCERA)
WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 113));
else
mainparent.Send_UDP_cmd(Totrans, 3000, 113);
break;
case SubscriberType.DISPATCHER:
Totrans = String.Format("#211#{0}#{1}#", selected_Subscriber.Imei, "224.20." + MainForm2.userIDX + ".1#0");//selected_Subscriber.IP
WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 211));
break;
}
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//CallsForm cf = new CallsForm();
//cf.Show();
}
#endregion
private void pictureBox2_Click(object sender, EventArgs e)
{
if (listViewSubscribers.ViewType == ListViewType.DetailsView)
listViewSubscribers.ViewType = ListViewType.IconsView;
else
listViewSubscribers.ViewType = ListViewType.DetailsView;
}
private void pbFilter_Click(object sender, EventArgs e)
{
pbFilterTime.Image = Dispatcher.Properties.Resources.filter_time_grey;
pbFilterType.Image = Dispatcher.Properties.Resources.filter_type_grey;
pbFilterUser.Image = Dispatcher.Properties.Resources.filter_user_grey;
pbFilterDirection.Image = Dispatcher.Properties.Resources.filter_direction_grey;
pbFilterTime.Tag = "disabled";
pbFilterType.Tag = "disabled";
pbFilterUser.Tag = "disabled";
pbFilterDirection.Tag = "disabled";
string filterName = "DateStart";
ListSortDirection sortDirection = ListSortDirection.Ascending;
if ((PictureBox)sender == pbFilterTime)
{
pbFilterTime.Image = Dispatcher.Properties.Resources.filter_time_black;
pbFilterTime.Tag = "enabled";
filterName = "DateStart";
// default sort direction for date start is descending
sortDirection = ListSortDirection.Descending;
}
else if ((PictureBox)sender == pbFilterType)
{
pbFilterType.Image = Dispatcher.Properties.Resources.filter_type_black;
pbFilterType.Tag = "enabled";
filterName = "callType";
}
else if ((PictureBox)sender == pbFilterUser)
{
pbFilterUser.Image = Dispatcher.Properties.Resources.filter_user_black;
pbFilterUser.Tag = "enabled";
filterName = "Initial";
}
else if ((PictureBox)sender == pbFilterDirection)
{
pbFilterDirection.Image = Dispatcher.Properties.Resources.filter_direction_black;
pbFilterDirection.Tag = "enabled";
filterName = "callDirection";
}
if (gridRecordings.GroupDescriptors.Count > 0 &&
gridRecordings.GroupDescriptors[0].Expression.Contains(filterName))
{
GroupDescriptor gd = gridRecordings.GroupDescriptors[0];
sortDirection = gd.Expression.Contains("ASC") ? ListSortDirection.Descending : ListSortDirection.Ascending;
}
// clear previous filters and add the new one
gridRecordings.GroupDescriptors.Clear();
GroupDescriptor groupDescriptor = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor(filterName, sortDirection) });
gridRecordings.GroupDescriptors.Add(groupDescriptor);
}
#region PLAY procedure
private MemoryStream RecorderStream1 = null;
private RawSourceWaveStream recordingWaveStream = null;
private WaveOut recordingWaveOut = null;
private void UnableToPlay_Tick(object sender, EventArgs e)
{
try
{
if (MainForm2.PlayingFile)
BackToPlay();
UnableToPlay.Stop();
UnableToPlay.Enabled = false;
}
catch (Exception ex)
{
SM.Debug("UnableToPlay_Tick:" + ex.ToString());
}
}
private void StopPlayTimer_Tick(object sender, EventArgs e)
{
try
{
if (MainForm2.PlayingFile)
BackToPlay();
StopPlayTimer.Stop();
StopPlayTimer.Enabled = false;
}
catch (Exception ex)
{
SM.Debug("Ex:" + ex.ToString());
}
}
public void BackToPlay()
{
try
{
MainForm2.PlayingFile = false;
}
catch (Exception ex)
{
SM.Debug("Unable to get back volume" + ex.ToString());
}
}
public void PlayFile(Int64 IdToPlay, Int32 TimerInterval)
{
if (TimerInterval == 0)
{
parent.DisplayToast("Unable to play recording", "The desired recording was not found. Probably it was deleted.");
return;
}
try
{
MainForm2.PlayingFile = true;
MainForm2.PlayingFileCount = 0;
UnableToPlay.Enabled = true;
UnableToPlay.Start();
StopPlayTimer.Interval = TimerInterval;
StopPlayTimer.Enabled = true;
StopPlayTimer.Start();
bool start = tcpAudio.Start(MainForm2.cfg.REC_IP, Convert.ToInt32(MainForm2.cfg.REC_audio_port));
RecorderStream1 = new MemoryStream();
Int64 id = (Int64)IdToPlay;
byte[] temp = BitConverter.GetBytes(id);
byte[] buff = new byte[temp.Length + 1];
buff[0] = 1;
int i = 1;
foreach (byte b in temp)
{
buff[i] = b;
i++;
}
tcpAudio.Send(buff);
}
catch (Exception ex)
{
SM.Debug("PlayFile:" + ex.ToString());
}
}
private void InitListToPlay()
{
try
{
tcpAudio = new TcpClass();
tcpAudio.OnMessageRecv += new TcpClass.MessageRecv(tcpAudio_OnMessageRecv);
tcpAudio.OnConnectionEnded += new TcpClass.ConnectionEnded(tcpAudio_OnConnectionEnded);
}
catch (Exception ex)
{
SM.Debug("InitListToPlay:" + ex.ToString());
}
}
void tcpAudio_OnMessageRecv(byte[] data, int recv)
{
try
{
RecorderStream1.Write(data, 0, recv);
MainForm2.PlayingFileCount++;
if (MainForm2.PlayingFileCount == 2)
{
UnableToPlay.Stop();
UnableToPlay.Enabled = false;
}
}
catch (Exception ex)
{
SM.Debug("tcpAudio_OnMessageRecv:" + ex.ToString());
}
}
void tcpAudio_OnConnectionEnded()
{
try
{
recordingWaveStream = new RawSourceWaveStream(new MemoryStream(RecorderStream1.ToArray()), waveInClass.WaveFormat);
recordingWaveOut.Init(recordingWaveStream);
recordingWaveOut.Play();
}
catch (Exception ex)
{
SM.Debug("Conection ended error:" + ex.ToString());
}
}
#endregion
#region voiceINIT
//public volatile NewAudio nVOice;
public volatile WaveIn waveInClass = null;
private volatile BufferedWaveProvider buffWaveProvider = null;
public volatile WaveOut waveOutClass = null;
public int selectedOUTDevice;
public string selectedOUTDeviceName = " ";
public int selectedINDevice;
public string selectedINDeviceName = " ";
public ArrayList soundINDevices = new ArrayList();
public ArrayList soundOUTDevices = new ArrayList();
EventHandler<WaveInEventArgs> waveInClassHandlerForDataAvailable = null;
public void StartnVoice()
{
try
{
if (waveOutClass != null)
{
waveOutClass.Dispose();
waveOutClass = null;
}
if (waveInClass != null)
{
waveInClass.DataAvailable -= waveInClassHandlerForDataAvailable;
waveInClass.Dispose();
waveInClass = null;
}
//selectedINDevice = selectedOUTDevice = 0;
if ((selectedINDevice != -1) && (selectedOUTDevice != -1))
{
try
{
/*nVOice = new NewAudio(selectedINDevice, selectedOUTDevice);
nVOice.OnVoiceRecv += new NewAudio.VoiceRecv(nVOice_OnNewDataRecv);
MainForm2.nVoiceforClose = nVOice;*/
Utils.WriteLine("Device IN:" + selectedINDevice + " Device OUT:" + selectedOUTDevice, ConsoleColor.Magenta);
waveInClass = new WaveIn();
waveInClass.DeviceNumber = selectedINDevice;
waveInClass.BufferMilliseconds = voicemanager_bufferMilliseconds;
waveInClassHandlerForDataAvailable = waveInClass_DataAvailable;
#if LINX || LINXB || EXCERA
if (MainForm2.recordingsDecide)
{
waveInClassHandlerForDataAvailable = waveInClass_DataAvailable_Recordings;
}
#endif
waveInClass.DataAvailable += waveInClassHandlerForDataAvailable;
int sampleRate = voicemanager_sampleRate;
int channels = 1;
waveInClass.WaveFormat = new NAudio.Wave.WaveFormat(sampleRate, voicemanager_bitDepth, channels);
waveInClass.StartRecording();
buffWaveProvider = new BufferedWaveProvider(waveInClass.WaveFormat);
waveOutClass = new WaveOut();
waveOutClass.DeviceNumber = selectedOUTDevice;
waveOutClass.Init(buffWaveProvider);
waveOutClass.Play();
recordingWaveOut = new WaveOut();
recordingWaveOut.DeviceNumber = selectedOUTDevice;
//MainForm2.waveInClassforClose = waveInClass;
//MainForm2.waveOutClassforClose = waveOutClass;
Utils.WriteLine("Init new WAVE module", ConsoleColor.Magenta);
}
catch (Exception ex)
{
SM.Debug("Error to start voice for ALL call" + ex.ToString());
}
}
}
catch (Exception ex)
{
SM.Debug("StartnVoice:" + ex.ToString());
}
}
void waveInClass_DataAvailable(object sender, WaveInEventArgs e)
{
try
{
if (PTTinprogres)
{
if (selected_Subscriber.canMakeSipCalls)
{
parent.SendSipVoice(selected_Subscriber.SipID.ToString(), e.Buffer, e.BytesRecorded, SipComponent.AudioFormat.PCM);
}
else
{
Utils.WriteLine($"Sending {e.BytesRecorded} voice bytes on multicast address {MainForm2.udp4Voice.mcastGroup} ");
MainForm2.udp4Voice.Send(e.Buffer, e.BytesRecorded);
}
}
}
catch (Exception ex)
{
SM.Debug("nVOice_OnNewDataRecv:" + ex.ToString());
}
}
void waveInClass_DataAvailable_Recordings(object sender, WaveInEventArgs e)
{
try
{
if (PTTinprogres)
{
if (selected_Subscriber.canMakeSipCalls)
{
parent.SendSipVoice(selected_Subscriber.SipID.ToString(), e.Buffer, e.BytesRecorded, SipComponent.AudioFormat.PCM);
// Send also voice on mBus so that AppServer will record
Utils.WriteLine($"[Rec] Sending {e.BytesRecorded} voice bytes on multicast address {MainForm2.udp4Voice.mcastGroup} ");
MainForm2.udp4Voice.Send(e.Buffer, e.BytesRecorded);
}
else
{
Utils.WriteLine($"[Rec] Sending {e.BytesRecorded} voice bytes on multicast address {MainForm2.udp4Voice.mcastGroup} ");
MainForm2.udp4Voice.Send(e.Buffer, e.BytesRecorded);
}
}
}
catch (Exception ex)
{
SM.Debug("nVOice_OnNewDataRecv:" + ex.ToString());
}
}
private void InputSoundList_Click(object sender, EventArgs e)
{
InitAudioInputDevices();
}
private void OutputSoundList_Click(object sender, EventArgs e)
{
InitAudioOutputDevices();
}
private void InitAudioInputDevices()
{
selectedINDevice = -1;
try
{
InputSoundList.Items.Clear();
int nrOfWaveInDevices = WaveIn.DeviceCount;
for (int j = 0; j < nrOfWaveInDevices; j++)
{
WaveInCapabilities deviceInvo = WaveIn.GetCapabilities(j);
sDevice dev;
dev.index = j;
dev.name = deviceInvo.ProductName.Trim();
soundINDevices.Add(dev);
InputSoundList.Items.Add(dev.name);
}
if (soundINDevices.Count > 0)
{
if (selectedINDevice < soundINDevices.Count)
{
bool found = false;
foreach (sDevice dev in soundINDevices)
{
if (dev.name == selectedINDeviceName)
{
found = true;
selectedINDevice = dev.index;
//InputSoundList.Text = dev.name;
InputSoundList.SelectedIndex = dev.index;
}
}
if (!found)
{
selectedINDevice = 0;
}
}
else
{
selectedINDevice = 0;
}
}
InputSoundList.SelectedIndex = selectedINDevice;
}
catch (Exception ex)
{
SM.Debug("ERROR in voice ini : " + ex.ToString());
}
}
private void InitAudioOutputDevices()
{
selectedOUTDevice = -1;
try
{
OutputSoundList.Items.Clear();
int nrOfWaveOUTDevices = WaveOut.DeviceCount;
for (int j = 0; j < nrOfWaveOUTDevices; j++)
{
WaveOutCapabilities deviceInvo = WaveOut.GetCapabilities(j);
sDevice dev;
dev.index = j;
dev.name = deviceInvo.ProductName.Trim();
soundOUTDevices.Add(dev);
OutputSoundList.Items.Add(dev.name);
}
if (soundOUTDevices.Count > 0)
{
if (selectedOUTDevice < soundOUTDevices.Count)
{
bool found = false;
foreach (sDevice dev in soundOUTDevices)
{
if (dev.name == selectedOUTDeviceName)
{
found = true;
selectedOUTDevice = dev.index;
//InputSoundList.Text = dev.name;
OutputSoundList.SelectedIndex = dev.index;
}
}
if (!found)
{
selectedOUTDevice = 0;
}
}
else
{
selectedOUTDevice = 0;
}
}
OutputSoundList.SelectedIndex = selectedOUTDevice;
}
catch (Exception ex)
{
SM.Debug("ERROR in voice ini : " + ex.ToString());
}
}
private void iniVoiceComponents()
{
selectedOUTDevice = -1;
selectedINDevice = -1;
try
{
InputSoundList.Items.Clear();
OutputSoundList.Items.Clear();
int nrOfWaveOUTDevices = WaveOut.DeviceCount;
for (int j = 0; j < nrOfWaveOUTDevices; j++)
{
WaveOutCapabilities deviceInvo = WaveOut.GetCapabilities(j);
sDevice dev;
dev.index = j;
dev.name = deviceInvo.ProductName.Trim();
soundOUTDevices.Add(dev);
OutputSoundList.Items.Add(dev.name);
}
if (soundOUTDevices.Count > 0)
{
if (selectedOUTDevice < soundOUTDevices.Count)
{
bool found = false;
foreach (sDevice dev in soundOUTDevices)
{
if (dev.name == selectedOUTDeviceName)
{
found = true;
selectedOUTDevice = dev.index;
//InputSoundList.Text = dev.name;
OutputSoundList.SelectedIndex = dev.index;
}
}
if (!found)
{
selectedOUTDevice = 0;
}
}
else
{
selectedOUTDevice = 0;
}
}
int nrOfWaveInDevices = WaveIn.DeviceCount;
for (int j = 0; j < nrOfWaveInDevices; j++)
{
WaveInCapabilities deviceInvo = WaveIn.GetCapabilities(j);
sDevice dev;
dev.index = j;
dev.name = deviceInvo.ProductName.Trim();
soundINDevices.Add(dev);
InputSoundList.Items.Add(dev.name);
}
if (soundINDevices.Count > 0)
{
if (selectedINDevice < soundINDevices.Count)
{
bool found = false;
foreach (sDevice dev in soundINDevices)
{
if (dev.name == selectedINDeviceName)
{
found = true;
selectedINDevice = dev.index;
//InputSoundList.Text = dev.name;
InputSoundList.SelectedIndex = dev.index;
}
}
if (!found)
{
selectedINDevice = 0;
}
}
else
{
selectedINDevice = 0;
}
}
// selectedOUTDevice = selectedINDevice = 0;
OutputSoundList.SelectedIndex = selectedOUTDevice;
InputSoundList.SelectedIndex = selectedINDevice;
}
catch (Exception ex)
{
SM.Debug("ERROR in voice ini : " + ex.ToString());
}
}
#endregion
~RadioTab()
{
//if(tcp!=null)tcp.Stop();
if (tcpAudio != null) tcpAudio.Stop();
}
private void listRecordings_MouseClick(object sender, MouseEventArgs e)
{
Console.WriteLine("INTO CLICK LIST");
PlayFile(3949747661, 7);
//PlayFile(((Recording)listRecordings.SelectedItem).RecID, ((Recording)listRecordings.SelectedItem).duration);
}
public Subscriber selected_Subscriber = null;
/// <summary>
/// Not used? Should be deleted?
/// </summary>
public Subscriber selected_Subscriber_PTT = null;
/// <summary>
/// Not used? Should be deleted?
/// </summary>
//private Subscriber field_subscriber_making_the_call = null;
private void listSubscribers_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listViewSubscribers.SelectedItems.Count == 0)
{
selected_Subscriber = selected_Subscriber_PTT = null;
return;
}
listFavorites.SelectedIndex = -1;
listFavorites.Update();
selected_Subscriber = selected_Subscriber_PTT = (Subscriber)listViewSubscribers.SelectedItems[0].DataBoundItem;
SetPTTButtonEnableDisable();
Update_call_selected();
}
private void SetPTTButtonEnableDisable()
{
if (selected_Subscriber != null && selected_Subscriber.SubscriberType != SubscriberType.DISPATCHER && !selected_Subscriber.canMakeSipCalls)
{
try
{
if (MainForm2.vehicleHT.ContainsKey(selected_Subscriber.DispatcherName))
{
((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).CheckPositionInSystem();
selected_Subscriber.Gw_and_radioID = ((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).GwandRadioID;
}
RadioGateway radioGw = (RadioGateway)MainForm2.radioGwHT[selected_Subscriber.Gw_and_radioID];
pbPTT.Enabled = radioGw.Alive;
pbPTT.Image = pbPTT.Enabled ? Dispatcher.Properties.Resources.r_ptt : Dispatcher.Properties.Resources.r_ptt_incoming;
}
catch
{
pbPTT.Enabled = false;
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_incoming;
}
}
else
{
pbPTT.Enabled = true;
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt;
}
if(selected_Subscriber.canMakeSipCalls)
{
pbPTT.Enabled = MainForm2.sipStatus;
pbPTT.Image = MainForm2.sipStatus ? Dispatcher.Properties.Resources.r_ptt : Dispatcher.Properties.Resources.r_ptt_incoming;
}
}
private void listFavorites_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listFavorites.SelectedItems.Count == 0)
{
selected_Subscriber = selected_Subscriber_PTT = null;
return;
}
listViewSubscribers.SelectedIndex = -1;
listViewSubscribers.Update();
selected_Subscriber = selected_Subscriber_PTT = (Subscriber)listFavorites.SelectedItems[0].DataBoundItem;
SetPTTButtonEnableDisable();
Update_call_selected();
}
private void listFavorites_ItemMouseClick(object sender, ListViewItemEventArgs e)
{
// Daca e doar un element in lista, vreau ca la click sa se apleleze procedura de selectie
if (listFavorites.Items.Count == 1)
listFavorites_SelectedIndexChanged(listFavorites, null);
}
private void Update_call_selected()
{
switch (selected_Subscriber.SubscriberType)
{
case SubscriberType.SUBSCRIBER:
lbPTT_to_unit.Text = String.Format(MainForm2.returnLNGString("forPrivatecallto"), selected_Subscriber.DispatcherName);
break;
case SubscriberType.GROUP:
lbPTT_to_unit.Text = String.Format(MainForm2.returnLNGString("forGroupcallto"), selected_Subscriber.DispatcherName);
break;
case SubscriberType.ALL:
lbPTT_to_unit.Text = String.Format(MainForm2.returnLNGString("forAllcall"), selected_Subscriber.DispatcherName);
break;
case SubscriberType.DISPATCHER:
lbPTT_to_unit.Text = String.Format(MainForm2.returnLNGString("forDispatchercallto"), selected_Subscriber.DispatcherName);
break;
}
}
#region Recive Data From MessageBus
private void CheckMessage_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = Computation(worker, e);
}
catch (Exception ex)
{
SM.Debug("Erorr start checkMessage:" + ex.ToString());
}
}
public volatile Int32 dataIntVOL = 0;
public volatile Int32 typeVOL = 0;
public volatile Int32 IdVOL = 0;
private volatile Boolean PTTinprogres = false;
public volatile Boolean ResponsePTT = false;
private volatile string GatewayAndRadioID = "";
public volatile Int32 callStatusVOL = 0;
public volatile Int32 callTypeVOL = 0;
public volatile Int32 grpIDVOL = 0;
private volatile Boolean Startrecevied = false;
private Dictionary<long, bool> startReceivedDict = new Dictionary<long, bool>();
//private CallsForm uniqueCallForm = null;
private Dictionary<string, CallsForm> callFormContainer = new Dictionary<string, CallsForm>();
public volatile Alarms voltmpx = null;
//public volatile System.Threading.Timer tclose125 = null;
private void Come_back_to_normal_PTT_state(object state)
{
try
{
if (this.InvokeRequired)
{
this.Invoke((Action)(() => { pbPTT.Image = Dispatcher.Properties.Resources.r_ptt; }));
}
else
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt;
}
catch (Exception ex)
{
SM.Debug("Ex101:" + ex.ToString());
}
}
private void CheckMessage_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
dataIntVOL = e.ProgressPercentage;
typeVOL = dataIntVOL % 1000;
IdVOL = dataIntVOL / 1000;
switch (typeVOL)
{
case 100:
/* if (IdVOL == 1)
{
TurnON();
isON = true; //intreb gaby cum da canalele
}
else
{
TurnOFF();
isON = false;
lbStatus.Text = radiooffline;
lbStatus.Update();
}*/
break;
case 999: //exitra timpu si opresc statia
/* rbAllCall.Enabled = true;
rbGroupCall.Enabled = true;
rbPrivateCall.Enabled = true;
rbAllCall.IsChecked = true;
TurnOFF();
PTTclicked = false;
lbStatus.Text = radiooffline;
lbStatus.Update*/
break;
case 998:
/* lbStatus.Text = btRem.Text + " " + MainForm2.returnLNGString("error");
btRem.Enabled = true;
EnableChALL();
PTT_enable();
PTTclicked = false;
parent.GeneralPTTclick = false;*/
break;
case 207:
/* if (IdVOL == 1)
{
chanelFree = false;
DisableALL();
}
else
{
chanelFree = true;
EnableALL();
}*/
break;
case 124:
/* SM.Debug("proccess 124 for IP:" + myIP);
TurnON();
ImgStat.Image = global::Dispatcher.Properties.Resources.green_status;
isON = true;
FirstChanle00 = false;
DisplayChChanel(IdVOL);
PTTinprogres = false; */
break;
case 115:
PTTinprogres = false;
Utils.WriteLine($"Received 115 commnad");
//confirmare mesajului de OFF
break;
case 116:
PTTinprogres = false;
Utils.WriteLine($"Received 116 commnad");
break;
case 117:
PTTinprogres = false;
Utils.WriteLine($"Received 117 commnad");
break;
case 121:
if (IdVOL == 1)
{
Utils.WriteLine($"RadioTab Handle121Command {IdVOL}", ConsoleColor.Cyan);
PTTinprogres = true;
ConfirmPTT_and_Start_Voice();
}
else
{
//set other status for button on response is wrong Talk with ADY
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
PTTinprogres = false;
}
ResponsePTT = true;
break;
case 10:
String reason = "unknown";
switch ((RADIO_STATUS)IdVOL)
{
case RADIO_STATUS.ALLcall_INIT:
reason = "All call";
break;
case RADIO_STATUS.ALLcall_INPROGRES:
reason = "All call";
break;
case RADIO_STATUS.CallEvent:
reason = "CallEvent";
break;
case RADIO_STATUS.ChannelQuery:
reason = "ChQuery";
break;
case RADIO_STATUS.DKEY:
reason = "Dkey";
break;
case RADIO_STATUS.EnableDisable:
reason = "En./Dis.";
break;
case RADIO_STATUS.FREE:
reason = "Free";
break;
case RADIO_STATUS.GroupCall_INIT:
reason = "GroupCall";
break;
case RADIO_STATUS.GroupCall_INPROGRES:
reason = "GroupCall";
break;
case RADIO_STATUS.HangTime:
reason = "HangTime";
break;
case RADIO_STATUS.OFF:
reason = "OFF";
break;
case RADIO_STATUS.PrivateCall_INIT:
reason = "Priv. Call";
break;
case RADIO_STATUS.PrivateCall_INPROGRES:
reason = "Priv. Call";
break;
case RADIO_STATUS.RemoteMonitor:
reason = "RM";
break;
case RADIO_STATUS.RemoteMonitor_INPROGRES:
reason = "RM";
break;
}
break;
case 122:
Handle122Command(IdVOL);
break;
case 221:
if (IdVOL == 1)
{
PTTinprogres = true;
RecivedData = true;
ConfirmPTT_and_Start_Voice();
}
else
{
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
PTTinprogres = false;
//RecivedData = false;
//receive data false ideea e ca daca aveam doua calluri simultan si unul se inchidea, daca pe celalalt il puneam pe principal nu mai venea voce
//pentru ca exista un singur receive data
RecivedData = MainForm2.PriorityIP != "";
}
break;
case 211:
PTTinprogres = false;
//RecivedData = false;
RecivedData = MainForm2.PriorityIP != "";
//uniqueCallForm.Close();
//uniqueCallForm = null;
if (callFormContainer.ContainsKey(PersonalIP) && callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
#region call patching
if (patchDictionary.ContainsKey("Dispatcher." + IdVOL))
EndCallPatch("Dispatcher", "Dispatcher." + IdVOL, IdVOL.ToString());
#endregion
}
break;
case 201:
string idtmp = "";
if (MainForm2.userIDHash[IdVOL] != null)
{
idtmp = (string)MainForm2.userIDHash[IdVOL];
if ((idtmp != null) && (idtmp != ""))
{
if (idtmp.Length > 17)
{
idtmp = idtmp.Remove(17);
idtmp += "...";
}
}
else idtmp = IdVOL.ToString();
}
else idtmp = IdVOL.ToString();
if (MainForm2.userIDHash[IdVOL] != null)
{
string id2 = (string)MainForm2.userIDHash[IdVOL];
//field_subscriber_making_the_call = new Subscriber()
//{
// DispatcherName = id2,
// SubscriberType = SubscriberType.DISPATCHER,
// ImageKey = "i_classic_bus_02",
// IconFilePath = MainForm2.GetIconPathForUnit(id2),
// IP = String.Format("224.20.{0}.1", IdVOL),
// Imei = IdVOL.ToString(),
// Favorite = false
//};
}
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
//}
if (!callFormContainer.ContainsKey(PersonalIP))
{
callFormContainer.Add(PersonalIP, null);
}
else
{
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
}
}
if (rcbBubble.Checked)
{
//uniqueCallForm = new CallsForm(IdVOL, idtmp, 0, 201, 4);
//uniqueCallForm.OnHeadset_Click += delegate(object s, CallsForm.ToggleClickEventArgs e2)
GetAvailablePosition();
callFormContainer[PersonalIP] = new CallsForm(IdVOL, idtmp, 0, 201, 4, PersonalIP);
callFormContainer[PersonalIP].Title = String.Format("SafeMobile - " + MainForm2.returnLNGString("callOnGateway"),
GetRadioGatewayForSubscriber(IdVOL)?.Name);
callFormContainer[PersonalIP].GatewayName = GetRadioGatewayForSubscriber(IdVOL)?.Name;
callFormContainer[PersonalIP].SetMute(MainForm2.PriorityIP == "");
if (MainForm2.PriorityIP == "") MainForm2.PriorityIP = PersonalIP;
callFormContainer[PersonalIP].OnHeadset_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
// user wants to mute the sound from this user
if (MainForm2.PriorityIP != "" && MainForm2.PriorityIP != e2.IP)
callFormContainer[MainForm2.PriorityIP].SetMute(false);
if (MainForm2.PriorityIP != e2.IP)
MainForm2.PriorityIP = e2.IP;
else
MainForm2.PriorityIP = "";
};
callFormContainer[PersonalIP].OnForm_Closing += delegate (object s, FormClosingEventArgs ef)
{
// on form closing event
if (((CallsForm)s)._IP == MainForm2.PriorityIP)
{
MainForm2.PriorityIP = "";
}
};
//uniqueCallForm.OnPlay_Click += delegate(object s, CallsForm.ToggleClickEventArgs e2)
callFormContainer[PersonalIP].OnPlay_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Dekey) sendDekey();
else if (e2.Type_of_message == CallsForm.Cmd_type_callForm.End_call) sendCallStop(e2.IMEI);
else if ((e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) || (e2.Type_of_message == CallsForm.Cmd_type_callForm.Stop_PTT))
{
String Ip = e2.IP;
if (e2.SubsType != SubscriberType.DISPATCHER)
Ip = String.Format("224.10.{0}", Valid_GwID_and_RadioID);
Subscriber tmpsub = new Subscriber
{
DispatcherName = e2.CallerName,
SubscriberType = e2.SubsType,
Sc_id = 0,
Imei = e2.IMEI,
Gw_and_radioID = Valid_GwID_and_RadioID,
IP = Ip,
Favorite = false,
canMakeSipCalls = !e2.IP.Contains("224.")
};
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) sendPTT(tmpsub, true);
else StopPTT(tmpsub);
}
};
//uniqueCallForm.Show();
callFormContainer[PersonalIP].Show();
}
RecivedData = true;
#region call patching
//if (patchDictionary.ContainsKey("Dispatcher." + IdVOL))
// StartCallPatch("Dispatcher", "Dispatcher." + IdVOL, IdVOL.ToString());
#endregion
break;
case 162:
if (IdVOL == 1)
{
string id = "";// just protect to manual dial
if (MainForm2.VehIMEIHash[selected_Subscriber.Imei] != null)
{
id = (string)MainForm2.VehIMEIHash[selected_Subscriber.Imei];
if ((id != null) && (id != ""))
{
if (id.Length > 17)
{
id = id.Remove(17);
id += "...";
}
}
else id = selected_Subscriber.Imei;
}
else
id = selected_Subscriber.Imei;
//if (MainForm2.VehIMEIHash[selected_Subscriber.Imei] != null)
//{
// id = (string)MainForm2.VehIMEIHash[selected_Subscriber.Imei];
// //((Vehicle)MainForm2.vehicleHT[name]).CheckPositionInSystem();
// field_subscriber_making_the_call = new Subscriber()
// {
// DispatcherName = id,
// SubscriberType = SubscriberType.SUBSCRIBER,
// ImageKey = "i_classic_bus_02",
// IconFilePath = MainForm2.GetIconPathForUnit(id),
// Sc_id = ((Vehicle)MainForm2.vehicleHT[id]).sc_id,
// Imei = ((Vehicle)MainForm2.vehicleHT[id]).IMEI,
// Gw_and_radioID = Valid_GwID_and_RadioID,
// IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
// Favorite = false
// };
//}
//else
//{
// field_subscriber_making_the_call = new Subscriber()
// {
// DispatcherName = selected_Subscriber.Imei,
// SubscriberType = SubscriberType.SUBSCRIBER,
// ImageKey = "i_classic_bus_02",
// IconFilePath = MainForm2.GetIconPathForUnit(selected_Subscriber.Imei),
// Sc_id = 0,
// Imei = selected_Subscriber.Imei,
// Gw_and_radioID = Valid_GwID_and_RadioID,
// IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
// Favorite = false
// };
//}
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
//}
if (!callFormContainer.ContainsKey(PersonalIP))
{
callFormContainer.Add(PersonalIP, null);
}
else
{
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
}
}
if (rcbBubble.Checked)
{
//uniqueCallForm = new CallsForm(Convert.ToInt64(selected_Subscriber.Imei), id, grpIDVOL, 162, callStatusVOL);
//uniqueCallForm.OnHeadset_Click += delegate(object s, CallsForm.ToggleClickEventArgs e2)
GetAvailablePosition();
callFormContainer[PersonalIP] = new CallsForm(Convert.ToInt64(selected_Subscriber.Imei), id, grpIDVOL, 162, callStatusVOL, PersonalIP);
callFormContainer[PersonalIP].Title = String.Format("SafeMobile - " + MainForm2.returnLNGString("callOnGateway"),
GetRadioGatewayForSubscriber(IdVOL)?.Name);
callFormContainer[PersonalIP].GatewayName = GetRadioGatewayForSubscriber(IdVOL)?.Name;
callFormContainer[PersonalIP].SetMute(MainForm2.PriorityIP == "");
if (MainForm2.PriorityIP == "") MainForm2.PriorityIP = PersonalIP;
callFormContainer[PersonalIP].OnHeadset_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
// user wants to mute the sound from this user
if (MainForm2.PriorityIP != "" && MainForm2.PriorityIP != e2.IP)
callFormContainer[MainForm2.PriorityIP].SetMute(false);
if (MainForm2.PriorityIP != e2.IP)
MainForm2.PriorityIP = e2.IP;
else
MainForm2.PriorityIP = "";
};
callFormContainer[PersonalIP].OnForm_Closing += delegate (object s, FormClosingEventArgs ef)
{
// on form closing event
if (((CallsForm)s)._IP == MainForm2.PriorityIP)
{
MainForm2.PriorityIP = "";
}
};
//uniqueCallForm.OnPlay_Click += delegate(object s, CallsForm.ToggleClickEventArgs e2)
callFormContainer[PersonalIP].OnPlay_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Dekey) sendDekey();
else if (e2.Type_of_message == CallsForm.Cmd_type_callForm.End_call) sendCallStop(e2.IMEI);
else if ((e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) || (e2.Type_of_message == CallsForm.Cmd_type_callForm.Stop_PTT))
{
String Ip = e2.IP;
if (e2.SubsType != SubscriberType.DISPATCHER)
Ip = String.Format("224.10.{0}", Valid_GwID_and_RadioID);
Subscriber tmpsub = new Subscriber
{
DispatcherName = e2.CallerName,
SubscriberType = e2.SubsType,
Sc_id = 0,
Imei = e2.IMEI,
Gw_and_radioID = Valid_GwID_and_RadioID,
IP = Ip,
Favorite = false,
canMakeSipCalls = !e2.IP.Contains("224.")
};
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) sendPTT(tmpsub, true);
else StopPTT(tmpsub);
}
};
//uniqueCallForm.Show();
callFormContainer[PersonalIP].Show();
}
}
else if (IdVOL == 2)
{
//SMSAlert
RemoteMonitorDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
RemoteMonitorDesktopAlert.ContentImage = global::Dispatcher.Properties.Resources.remmonitor24x20;
String html_message = "<span><size=11><color=blue>" + MainForm2.returnLNGString("rem") + ": " + selected_Subscriber.DispatcherName + " </span>";
RemoteMonitorDesktopAlert.ContentText = "<html>" + html_message + "</html>"; // mesajul din interior editat cu html
String title = MainForm2.returnLNGString("remfail");
RemoteMonitorDesktopAlert.CaptionText = title;
//SMSDesktopAlert.ContentText = (e.UserState as String);
RemoteMonitorDesktopAlert.Show();
}
break;
case 172:
//RecivedData = false;
RecivedData = MainForm2.PriorityIP != "";
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
//}
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
}
break;
case 222:
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
//}
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
}
break;
case 123:
/*
if (IdVOL == 1)
{
PTTinprogres = true;
ConfirmPTT_and_Start_Voice();
}
else
{
// ADY if we put other image for call rejected
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
PTTinprogres = false;
PTTclicked = false;
}
ResponsePTT = true;
*/
Handle123Command(IdVOL);
break;
case 125:
callStatusVOL = (e.UserState as transfer125).callStatus;
callTypeVOL = (e.UserState as transfer125).callType;
grpIDVOL = (e.UserState as transfer125).grpID;
String gwID = (e.UserState as transfer125).gwID;
String radioGwID = (e.UserState as transfer125).radioGwID;
Int64 IdVOLx = (e.UserState as transfer125).intvalID;
Handle125Command(gwID, radioGwID, callStatusVOL, callTypeVOL, grpIDVOL, IdVOLx);
break;
}
}
catch (Exception ex)
{
SM.Debug("Error processmessage on radio:" + ex.ToString());
}
}
private void Handle122Command(int result)
{
Utils.WriteLine($"RadioTab Handle122Command {result}", ConsoleColor.Cyan);
if (result == 1)
{
PTTinprogres = true;
ConfirmPTT_and_Start_Voice();
try
{
if (MainForm2.vehicleHT.Contains(selected_Subscriber.DispatcherName))
((Vehicle)MainForm2.vehicleHT[selected_Subscriber.DispatcherName]).EventLists.Add(new Alarms(rep_type.CALLSEND, DateTime.Now, "", ""));
//FirstTimePriv = DateTime.Now;
}
catch (Exception ex)
{
SM.Debug("Erorr adding 122:" + ex.ToString());
}
}
else
{
// ADY if we put other image for call rejected
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1500, System.Threading.Timeout.Infinite);
PTTinprogres = false;
}
ResponsePTT = true;
}
private void Handle123Command(int result)
{
Utils.WriteLine($"RadioTab Handle123Command {result}", ConsoleColor.Cyan);
if (result == 1)
{
PTTinprogres = true;
ConfirmPTT_and_Start_Voice();
}
else
{
// ADY if we put other image for call rejected
pbPTT.Image = Dispatcher.Properties.Resources.r_ptt_end;
System.Threading.Timer t1 = new System.Threading.Timer(Come_back_to_normal_PTT_state, null, 1000, System.Threading.Timeout.Infinite);
PTTinprogres = false;
}
ResponsePTT = true;
}
private RadioGateway GetRadioGatewayForSubscriber(Int64 radioID)
{
RadioGateway result = null;
if (MainForm2.VehIMEIHash[radioID.ToString()] != null)
{
if (MainForm2.vehicleHT[MainForm2.VehIMEIHash[radioID.ToString()]] != null)
{
((Vehicle)MainForm2.vehicleHT[MainForm2.VehIMEIHash[radioID.ToString()]]).CheckPositionInSystem();
GatewayAndRadioID = ((Vehicle)MainForm2.vehicleHT[MainForm2.VehIMEIHash[radioID.ToString()]]).GwandRadioID;
if (MainForm2.radioGwHT[GatewayAndRadioID] != null)
{
result = ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]);
}
}
}
return result;
}
public void OnRadioGatewayStateChanged(RadioGateway gateway, RadioState state)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
OnRadioGatewayStateChanged(gateway, state);
});
}
else
{
rlvGatewayStatus.BeginUpdate();
RadioGateway rg = radiogateways.Find(d => d.Name.Equals(gateway.Name));
if(rg != null)
rg.State1 = state;
rlvGatewayStatus.EndUpdate();
}
}
private static readonly object lockerIP = new object();
/// <summary>
/// Handles 125 command in RadioTab
/// </summary>
/// <param name="callStatus">The State of the call: 1 - Initiated, 2 - HangTime, 3 - Ended</param>
/// <param name="callType">The type of the call: 101 - All Call, 102 - Private Call, 103 - Group Call, 104 - Emergency Call </param>
/// <param name="targetID">The ID of the field or group which received the call</param>
/// <param name="sourceRadioID">The ID of the radio which initiated the call</param>
private void Handle125Command(String gwId, String radioGWId, int callStatus, int callType, int targetID, long sourceRadioID, ContactType sourceType = ContactType.UNIT)
{
//Utils.WriteLine($"Received CallStatus Update : {callStatus} | {callType} | {targetID} | {sourceRadioID} || {sourceType}", ConsoleColor.Yellow);
RadioGateway rg = null;
if (MainForm2.radioGwHT.ContainsKey(gwId+"." + radioGWId))
rg = ((RadioGateway)MainForm2.radioGwHT[gwId + "." + radioGWId]);
if (MainForm2.VehIMEIHash[sourceRadioID.ToString()] != null)
{
if (MainForm2.vehicleHT[MainForm2.VehIMEIHash[sourceRadioID.ToString()]] != null)
{
((Vehicle)MainForm2.vehicleHT[MainForm2.VehIMEIHash[sourceRadioID.ToString()]]).CheckPositionInSystem();
GatewayAndRadioID = ((Vehicle)MainForm2.vehicleHT[MainForm2.VehIMEIHash[sourceRadioID.ToString()]]).GwandRadioID;
if (MainForm2.radioGwHT[GatewayAndRadioID] != null)
{
if (((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Broadband || ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Tier3Radio)
{
if (callTypeVOL == 102 && MainForm2.userIDX != grpIDVOL)
{
return;
}
}
}
}
}
// Call initiated
if (!startReceivedDict.ContainsKey(sourceRadioID))
startReceivedDict.Add(sourceRadioID, false);
if (callStatusVOL == 1)
{
try
{
//if (!Startrecevied)
if (startReceivedDict[sourceRadioID] == false)
{
try
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("CallStat:" + callStatusVOL + " calltype:" + callTypeVOL + " grpID:" + grpIDVOL);
Console.ResetColor();
string id = "";
if (sourceType == ContactType.UNIT)
{
if (MainForm2.VehIMEIHash[sourceRadioID.ToString()] != null) // Check if source radio id is a unit
{
id = (string)MainForm2.VehIMEIHash[sourceRadioID.ToString()];
if ((id != null) && (id != ""))
{
if (id.Length > 17)
{
id = id.Remove(17);
id += "...";
}
}
else id = sourceRadioID.ToString();
}
else id = sourceRadioID.ToString();
}
else if (sourceType == ContactType.USER)
{
if (MainForm2.userIDHash.ContainsKey((int)sourceRadioID)) // check if source radio id is a dispatcher (for sip group calls)
{
id = MainForm2.userIDHash[(int)sourceRadioID].ToString();
}
else id = sourceRadioID.ToString();
}
else
id = sourceRadioID.ToString();
/*lbIDValue.Text = id;
lbStatus.Text = id;
if (callTypeVOL == 101) lbChanel.Text = rbAllCall.Text;
else if (callTypeVOL == 103) lbChanel.Text = rbGroupCall.Text + " (" + grpIDVOL + ")";
else if (callTypeVOL == 102) lbChanel.Text = rbPrivateCall.Text;
if (callTypeVOL == 101) rbAllCall.IsChecked = true;
else if (callTypeVOL == 103) { rbGroupCall.IsChecked = true; tbGroupCallId.Text = grpIDVOL.ToString(); }
else if (callTypeVOL == 102) { rbPrivateCall.IsChecked = true; tbPrivateCallId.Text = IdVOLx.ToString(); }
else rbAllCall.IsChecked = true; // add new for bug858
rbAllCall.Enabled = false;
rbGroupCall.Enabled = false;
rbPrivateCall.Enabled = false;*/
//field_subscriber_making_the_call = new Subscriber();
//if (MainForm2.VehIMEIHash[sourceRadioID.ToString()] != null)
//{
// id = (string)MainForm2.VehIMEIHash[sourceRadioID.ToString()];
// field_subscriber_making_the_call = new Subscriber()
// {
// DispatcherName = id,
// SubscriberType = SubscriberType.SUBSCRIBER,
// ImageKey = "i_classic_bus_02",
// Sc_id = ((Vehicle)MainForm2.vehicleHT[id]).sc_id,
// Imei = ((Vehicle)MainForm2.vehicleHT[id]).IMEI,
// IconFilePath = MainForm2.GetIconPathForUnit(id),
// Gw_and_radioID = Valid_GwID_and_RadioID,
// IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
// Favorite = false
// };
//}
//else
//{
// field_subscriber_making_the_call = new Subscriber()
// {
// DispatcherName = sourceRadioID.ToString(),
// SubscriberType = SubscriberType.SUBSCRIBER,
// ImageKey = "i_classic_bus_02",
// Sc_id = 0,
// IconFilePath = MainForm2.GetIconPathForUnit(sourceRadioID.ToString()),
// Imei = sourceRadioID.ToString(),
// Gw_and_radioID = Valid_GwID_and_RadioID,
// IP = String.Format("224.10.{0}", Valid_GwID_and_RadioID),
// Favorite = false
// };
//}
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
//}
if (!callFormContainer.ContainsKey(PersonalIP))
{
callFormContainer.Add(PersonalIP, null);
}
else
{
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
}
}
if (rcbBubble.Checked)
{
//uniqueCallForm = new CallsForm(sourceRadioID, id, grpIDVOL, callTypeVOL, callStatusVOL);
//uniqueCallForm.OnHeadset_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
GetAvailablePosition();
//check if radio is in emergency and isn't another emergency call in progress
if (MainForm2.vehicleHT.ContainsKey(id))
{
if (((Vehicle)MainForm2.vehicleHT[id]).is_emergency && PriorityEmergency.Count == 0)
{
if (MainForm2.PriorityIP != "")
callFormContainer[MainForm2.PriorityIP].SetMute(false);
MainForm2.PriorityIP = "";
PriorityEmergency.Add(id, true);
}
}
string personalIP = PersonalIP;
callFormContainer[personalIP] = new CallsForm(sourceRadioID, id, grpIDVOL, callTypeVOL, callStatusVOL, personalIP);
callFormContainer[PersonalIP].Title = String.Format("SafeMobile - " + MainForm2.returnLNGString("callOnGateway"),
rg?.Name);
callFormContainer[PersonalIP].GatewayName = rg?.Name;
callFormContainer[personalIP].SetMute(MainForm2.PriorityIP == "");
if (MainForm2.vehicleHT.ContainsKey(id))
{
if (((Vehicle)MainForm2.vehicleHT[id]).is_emergency)
{
callFormContainer[personalIP].SetEmergencyColorBackground();
}
}
if (MainForm2.PriorityIP == "") MainForm2.PriorityIP = personalIP;
// Check if is sip call
bool isSipCall = false;
int sipID;
if (int.TryParse(personalIP, out sipID))
{
isSipCall = true;
}
callFormContainer[personalIP].OnHeadset_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
// user wants to mute the sound from this user
if (MainForm2.PriorityIP != "" && MainForm2.PriorityIP != e2.IP)
callFormContainer[MainForm2.PriorityIP].SetMute(false);
if (MainForm2.PriorityIP != e2.IP)
MainForm2.PriorityIP = e2.IP;
else
MainForm2.PriorityIP = "";
PriorityEmergency = new Dictionary<string, bool>();
};
callFormContainer[personalIP].OnForm_Closing += delegate (object s, FormClosingEventArgs ef)
{
// on form closing event
if (((CallsForm)s)._IP == MainForm2.PriorityIP)
{
MainForm2.PriorityIP = "";
}
if (PriorityEmergency.Count > 0)
{
if (PriorityEmergency.ContainsKey(((CallsForm)s).name))
PriorityEmergency = new Dictionary<string, bool>();
}
};
//uniqueCallForm.OnPlay_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
callFormContainer[personalIP].OnPlay_Click += delegate (object s, CallsForm.ToggleClickEventArgs e2)
{
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Dekey)
{
// Check if is sip call
if (isSipCall)
{
// Dekey for linx call
CloseSipCall(id);
}
else
sendDekey();
}
else if (e2.Type_of_message == CallsForm.Cmd_type_callForm.End_call)
{
if (isSipCall)
{
// Make dekey
CloseSipCall(id);
}
else
sendCallStop(e2.IMEI);
}
else if ((e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) || (e2.Type_of_message == CallsForm.Cmd_type_callForm.Stop_PTT))
{
Valid_GwID_and_RadioID = responseGW;
String Ip = e2.IP;
if (e2.SubsType != SubscriberType.DISPATCHER)
Ip = String.Format("224.10.{0}", Valid_GwID_and_RadioID);
Subscriber tmpsub = new Subscriber
{
DispatcherName = e2.CallerName,
SubscriberType = e2.SubsType,
Sc_id = 0,
Imei = e2.IMEI,
Gw_and_radioID = Valid_GwID_and_RadioID,
IP = Ip,
Favorite = false,
canMakeSipCalls = !e2.IP.Contains("224."),
SipID = e2.SubsType == SubscriberType.SUBSCRIBER ? ((Vehicle)MainForm2.vehicleHT[id]).sipID :
(
MainForm2.GroupCPSIDOnlyHashWithoutCategory.ContainsKey(e2.IMEI + Valid_GwID_and_RadioID) ?
MainForm2.GroupCPSIDOnlyHashWithoutCategory[e2.IMEI + Valid_GwID_and_RadioID].SipID :
-1
)
};
if (e2.Type_of_message == CallsForm.Cmd_type_callForm.Start_PTT) sendPTT(tmpsub, true);
else StopPTT(tmpsub);
}
};
//uniqueCallForm.Show();
callFormContainer[personalIP].Show();
}
RecivedData = true;
voltmpx = null;
if ((MainForm2.VehIMEIHash[sourceRadioID.ToString()] != null) && (((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[sourceRadioID.ToString()]]) != null))
{
foreach (Alarms obj in ((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[sourceRadioID.ToString()]]).EventLists)
if (obj.type == rep_type.CALLRECIVE) voltmpx = obj;
if ((voltmpx != null) && (voltmpx.descript == ""))
((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[sourceRadioID.ToString()]]).EventLists.Remove(voltmpx);
((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[sourceRadioID.ToString()]]).EventLists.Add(new Alarms(rep_type.CALLRECIVE, DateTime.Now, "", ""));
}
}
catch (Exception ex)
{
SM.Debug("Erorr adding 125:" + ex.ToString());
}
}
}
catch (Exception ex)
{
SM.Debug("Error on 125 with status 1 (begin call):" + ex.ToString());
}
//Startrecevied = true;
startReceivedDict[sourceRadioID] = true;
if (patchDictionary.ContainsKey("Gateway." + responseGW))
StartCallPatch("Gateway", "Gateway." + responseGW, responseGW);
}
else
{
try
{
//if (Startrecevied)
if (startReceivedDict[sourceRadioID] == true)
{
}
}
catch (Exception ex)
{
SM.Debug("Error on 125 with status 2 or 3 (end call or hang time):" + ex.ToString());
}
//Startrecevied = false;
startReceivedDict[sourceRadioID] = false;
if (callStatusVOL == 2)
{
//RecivedData = false;
RecivedData = MainForm2.PriorityIP != "";
//if (uniqueCallForm != null)
// uniqueCallForm.UpdateCallStatus(callStatusVOL);
if (callFormContainer.ContainsKey(PersonalIP))
{
if (callFormContainer[PersonalIP] != null)
callFormContainer[PersonalIP].UpdateCallStatus(callStatusVOL);
}
}
else if (callStatusVOL == 3)
{
RecivedData = false;
RecivedData = MainForm2.PriorityIP != "";
//if (uniqueCallForm != null)
//{
// uniqueCallForm.Close();
// uniqueCallForm = null;
// field_subscriber_making_the_call = null;
//}
if (callFormContainer.ContainsKey(PersonalIP))
{
if (callFormContainer[PersonalIP] != null)
{
if (callFormContainer[PersonalIP].RequestForClosing())
callFormContainer[PersonalIP] = null;
//RearrangeCallForm();
//field_subscriber_making_the_call = null;
}
}
if (patchDictionary.ContainsKey("Gateway." + responseGW))
{
if (runningPatches.Contains(responseGW))
EndCallPatch("Gateway", "Gateway." + responseGW, responseGW);
}
}
// if (tclose125 != null)
// tclose125.Dispose();
}
}
public volatile ArrayList WatchList = new ArrayList();
public volatile ArrayList ClearList = new ArrayList();
private volatile Boolean proces124 = false;
private volatile Boolean proces125 = false;
private volatile Boolean proces111or112or113 = false;
private volatile Boolean proces111or112or113FALSE = false;
private volatile Boolean proces121or122or123 = false;
private volatile Boolean proces101or102or103 = false;
private volatile Boolean procesReport = true;
private volatile Int32 Idproces = 0;
private volatile Int32 Limitsend = 0;
private volatile Int32 X = 0;
private volatile String volSTR = "";
public volatile transfer125 tmptransVOL = null;
long Computation(BackgroundWorker worker, DoWorkEventArgs e)
{
while (MainForm2.isRunning)
{
try
{
proces124 = false;
proces125 = false;
proces111or112or113 = false; proces111or112or113FALSE = false;
proces121or122or123 = false;
proces101or102or103 = false;
Idproces = 0;
lock (this)
{
X = 0;
while (X < WatchList.Count)
{
//SM.Debug("in comands " + myIP);
volSTR = (String)WatchList[X];
if (mainparent.Listcmd[volSTR] == null)
ClearList.Add(volSTR);
else
{
if (!((TimerAndResp)mainparent.Listcmd[volSTR]).wait)
{
if (((TimerAndResp)mainparent.Listcmd[volSTR]).Respose)
{
Int32 tmp = (Int32)((TimerAndResp)mainparent.Listcmd[volSTR]).intval * 1000 + ((TimerAndResp)mainparent.Listcmd[volSTR]).typeID;
if (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID == 125)
{
tmp = 0 * 1000 + ((TimerAndResp)mainparent.Listcmd[volSTR]).typeID;
tmptransVOL = new transfer125(((TimerAndResp)mainparent.Listcmd[volSTR]).callStatus, ((TimerAndResp)mainparent.Listcmd[volSTR]).callType, ((TimerAndResp)mainparent.Listcmd[volSTR]).GrpID, ((TimerAndResp)mainparent.Listcmd[volSTR]).intval);
tmptransVOL.gwID = ((TimerAndResp)mainparent.Listcmd[volSTR]).gwID;
tmptransVOL.radioGwID = ((TimerAndResp)mainparent.Listcmd[volSTR]).radioGwID;
proces125 = true;
}
//displayStat
if (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID == 124) { proces124 = true; Limitsend = 0; }
if ((((TimerAndResp)mainparent.Listcmd[volSTR]).typeID > 120) && (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID < 124)) { proces121or122or123 = true; Limitsend = 0; }
procesReport = true;
if ((tmp > 2114) && (tmp < 2118))
{
if (tmp == 2115) Idproces = 111;
else if (tmp == 2116) Idproces = 112;
else Idproces = 113;
Limitsend++;
proces111or112or113FALSE = true;
procesReport = false;
}
if (procesReport)
{
if (!proces125)
worker.ReportProgress(tmp);
else
worker.ReportProgress(tmp, tmptransVOL);
}
}
else
{
if (((((TimerAndResp)mainparent.Listcmd[volSTR]).typeID > 110) && (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID < 114)) || (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID == 104) || (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID == 161))
{
proces111or112or113 = true;
Idproces = ((TimerAndResp)mainparent.Listcmd[volSTR]).typeID;
}
if (((((TimerAndResp)mainparent.Listcmd[volSTR]).typeID > 100) && (((TimerAndResp)mainparent.Listcmd[volSTR]).typeID < 104)))
{
proces101or102or103 = true;
//Idproces = ((TimerAndResp)mainparent.Listcmd[obj]).typeID;
}
}
mainparent.Listcmd.Remove(volSTR);
ClearList.Add(volSTR);
/* if ((FirstChanle00) && !proces124)
{
worker.ReportProgress(1999);//sc_id =1 (fake) si comanda 999
isON = false;
FirstChanle00 = false;
}*/
}
}
X++;
}
}
foreach (String obj in ClearList)
WatchList.Remove(obj);
ClearList.Clear();
// ciudat remove 104 pentru care a venit 124
String tmpIdtoRemove = "";
if (proces124)
{
foreach (String obj in WatchList)
if (((TimerAndResp)mainparent.Listcmd[obj]).typeID == 104)
{
tmpIdtoRemove = obj;
break;
}
if (tmpIdtoRemove != "") WatchList.Remove(tmpIdtoRemove);
}
//SM.Debug("Value for proces121or122or123:" + proces121or122or123 + " and OUTBEFORE:"+OUTBEFORE);
//if ((proces121or122or123) && (OUTBEFORE)) callStopProcedure(true);
if (proces101or102or103) worker.ReportProgress(1115);
if (proces111or112or113 || proces111or112or113FALSE)
{
if (Limitsend < 6)
{
if (Idproces == 111)
{
if (proces111or112or113) ;//Stop_PTT(String.Format("224.20.{0}.1", MainForm2.userIDX));
else
{
WatchList.Add(mainparent.Send_delay(String.Format("#111#{0}#{1}#", selected_Subscriber.Gw_and_radioID, selected_Subscriber.IP), 3000, 111, 3000));
}
}
else if (Idproces == 112)
{
//prevent resending private excera doesn't have gateway
//if (MainForm2.radioType == RADIOTYPE.EXCERA)
// return 0;
String Totrans = "#112#" + selected_Subscriber.Gw_and_radioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
if (proces111or112or113) WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 112));
else WatchList.Add(mainparent.Send_delay(Totrans, 3000, 112, 3000));
}
else if (Idproces == 113)
{
//prevent resending private excera doesn't have gateway
//if (MainForm2.radioType == RADIOTYPE.EXCERA)
// return 0;
String Totrans = "#113#" + selected_Subscriber.Gw_and_radioID + "." + selected_Subscriber.Imei + "#" + "224.20." + MainForm2.userIDX + ".1" + "#";
if (proces111or112or113) WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 113));
else WatchList.Add(mainparent.Send_delay(Totrans, 3000, 113, 3000));
}
else if (Idproces == 161)
{
worker.ReportProgress(1998);//sc_id =1 (fake) si comanda 999
}
Limitsend++;
}
else //station come back to normal state
{
worker.ReportProgress(1999);//sc_id =1 (fake) si comanda 999
}
}
}
catch (Exception ex)
{
SM.Debug("Error on radio list" + ex.ToString());
}
Thread.Sleep(10);
if (MainForm2.ClosingApp)
{
SM.Debug("ComputMess Voice: CancellationPending in Radio: ");
e.Cancel = true;
return 1;
}
}
return 0;
}
#endregion
#region STYLE UI ELEMENTS
private void listSubscribers_VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e)
{
if (e.VisualItem is IconListViewVisualItem)
{
//Utils.WriteLine("listSubscribers_VisualItemCreating");
e.VisualItem = new SubscriberVisualListItem();
((SubscriberVisualListItem)e.VisualItem).OnFavorite_Click += delegate (object s, SubscriberVisualListItem.ToggleClickEventArgs ee)
{
Utils.WriteLine("Fav is " + ee.subscriber.DispatcherName + " | " + ee.isActive);
if (ee.subscriber.SubscriberType == SubscriberType.SUBSCRIBER)
{
// update isFavorite Value
if (MainForm2.VehIMEIHash.ContainsKey(ee.subscriber.Sc_id + ""))
(((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[ee.subscriber.Sc_id + ""]])).is_favorite = ee.isActive;
// add to hash the new value for isFavorite
VisualSettings.InsertUpdateHTforVisualItems("isFav", ee.subscriber.Sc_id + "", ee.isActive + "");
}
else
{
// add to hash the new value for isFavorite
//am pus variabila add pentru cazul in care am doua grupuri pe doua gatewayuri diferite cu acelasi imei
string add = ee.subscriber.SubscriberType == SubscriberType.GROUP ? ee.subscriber.Gw_and_radioID : "_" + ee.subscriber.DispatcherName;
VisualSettings.InsertUpdateHTforVisualItems("isFav", ee.subscriber.SubscriberType.ToString() + "_"
+ ee.subscriber.Imei + add + "", ee.isActive + "");
}
ListViewDataItem item = listViewSubscribers.Items.FirstOrDefault(d => d.DataBoundItem == ee.subscriber);
if (item != null)
{
listViewSubscribers.BeginUpdate();
Subscriber sub = (item.DataBoundItem as Subscriber);
sub.Favorite = ee.isActive;
sub.NrOfUpdates++;
listViewSubscribers.EndUpdate();
}
//listFavorites.DataSource = subscribersList;
FilterDescriptor valueFilter = new FilterDescriptor("Favorite", FilterOperator.IsEqualTo, (Boolean)true);
listFavorites.FilterDescriptors.Remove("Favorite");
listFavorites.FilterDescriptors.Add(valueFilter);
};
((SubscriberVisualListItem)e.VisualItem).OnTextSend_Req += delegate (object s, SubscriberVisualListItem.TextSendEventArgs ee)
{
//Utils.WriteLine("Text is " + ee.subscriber.DispatcherName + " | " + ee.text);
//String Totrans = "#142#" + ee.subscriber.Gw_and_radioID + "." + ee.subscriber.Imei + "#" + ee.text + "#" + (int)DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime()) + "#";
//String Totrans = "#142#" + ee.subscriber.Gw_and_radioID + "." + ee.subscriber.Imei + "#" + ee.text + "#" + (int)DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime()) + "#" +
// MainForm2.userIDX + "#";
////((MainForm2)(this.Parent)).Send_UDP_cmd(Totrans, 0, 0);
//mainparent.Send_UDP_cmd(Totrans, 0, 0);
//mainparent.DisplayToast(MainForm2.returnLNGString("txtMsgTo") + " " + ee.subscriber.DispatcherName, string.Format(MainForm2.returnLNGString("msgHTML"), ee.text));
if (ee.subscriber.SubscriberType == SubscriberType.SUBSCRIBER)
parent.SendSmsOnMBus(ee.text, ee.subscriber.Sc_id, (int)DateTime.Now.ToUniversalTime().DateTo70Format());
else if (ee.subscriber.SubscriberType == SubscriberType.GROUP)
{
//Group grp = ((Group)MainForm2.TalkGroups[0]);
parent.SendSMSGroup(ee.text, ee.subscriber.Id, 0, ee.subscriber.DispatcherName);
}
};
((SubscriberVisualListItem)e.VisualItem).OnRemote_Click += delegate (object s, SubscriberVisualListItem.ToggleClickEventArgs ee)
{
//Utils.WriteLine("Remote is " + ee.subscriber.DispatcherName + " | " + ee.isActive);
sendRemoteMOnitor(ee.subscriber);
mainparent.DisplayToast(MainForm2.returnLNGString("Remotemonitorfor") + " " + ee.subscriber.DispatcherName, MainForm2.returnLNGString("remoteMonitorHTML"));
};
}
}
private void listSubscribers_VisualItemFormatting(object sender, ListViewVisualItemEventArgs e)
{
// write the gateway name to the topRight element
if (e.VisualItem is SubscriberVisualListItem && e.VisualItem.Data.DataBoundItem is Subscriber)
(e.VisualItem as SubscriberVisualListItem).topRightElement.Text = (e.VisualItem.Data.DataBoundItem as Subscriber).GatewayName;
//Utils.WriteLine("listSubscribers_VisualItemFormatting");
if (e.VisualItem.Selected)
{
e.VisualItem.DrawFill = true;
e.VisualItem.BackColor = MainForm2.GridSelectedRow;
e.VisualItem.NumberOfColors = 1;
}
else
e.VisualItem.DrawFill = false;
GroupDescriptor descriptor = null;
if ((descriptor = listViewSubscribers.GroupDescriptors[0]) != null)
{
if (descriptor.Expression.Contains("Online"))
{
BaseListViewGroupVisualItem groupItem = e.VisualItem as BaseListViewGroupVisualItem;
if (groupItem != null)
{
groupItem.Font = new Font("Segoe UI", 10f, FontStyle.Bold);
groupItem.ForeColor = Color.Black;
groupItem.Text = (groupItem.Data.Text.ToLower().Equals("true") ? "Online" : "Offline")
+ " [" + ((ListViewDataItemGroup)groupItem.Data).Items.Count + "]";
}
}
else if (descriptor.Expression.Contains("SubscriberTypeRegion"))
{
BaseListViewGroupVisualItem groupItem = e.VisualItem as BaseListViewGroupVisualItem;
if (groupItem != null)
{
groupItem.Font = new Font("Segoe UI", 10f, FontStyle.Bold);
groupItem.ForeColor = Color.Black;
groupItem.Text = (groupItem.Data.Text)
+ " [" + ((ListViewDataItemGroup)groupItem.Data).Items.Count + "]";
}
}
}
}
private void listFavorites_VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e)
{
if (e.VisualItem is IconListViewVisualItem)
{
e.VisualItem = new SubscriberVisualListItem();
((SubscriberVisualListItem)e.VisualItem).OnFavorite_Click += delegate (object s, SubscriberVisualListItem.ToggleClickEventArgs ee)
{
Utils.WriteLine("Fav is " + ee.subscriber.DispatcherName + " | " + ee.isActive);
if (ee.subscriber.SubscriberType == SubscriberType.SUBSCRIBER)
{
if (MainForm2.VehIMEIHash.ContainsKey(ee.subscriber.Imei + ""))
{
(((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[ee.subscriber.Imei + ""]])).is_favorite = ee.isActive;
}
// add to hash the new value for isFavorite
VisualSettings.InsertUpdateHTforVisualItems("isFav", ee.subscriber.Sc_id + "", ee.isActive + "");
//????///VisualSettings.InsertUpdateHTforVisualItems("onMap", ee.subscriber.Sc_id + "", ee.isActive + "");
}
else
{
// add to hash the new value for isFavorite
//am pus variabila add pentru cazul in care am doua grupuri pe doua gatewayuri diferite cu acelasi imei
string add = ee.subscriber.SubscriberType == SubscriberType.GROUP ? ee.subscriber.Gw_and_radioID : "_" + ee.subscriber.DispatcherName;
VisualSettings.InsertUpdateHTforVisualItems("isFav", ee.subscriber.SubscriberType.ToString() + "_"
+ ee.subscriber.Imei + add + "", ee.isActive + "");
}
/*
ListViewDataItem item = listViewSubscribers.Items.FirstOrDefault(d => d.DataBoundItem == ee.subscriber);
if (item != null)
{
Subscriber sub = (item.DataBoundItem as Subscriber);
sub.Favorite = ee.isActive;
sub.NrOfUpdates = sub.NrOfUpdates + 1;
}
*/
ListViewDataItem item = listViewSubscribers.Items.FirstOrDefault(d => d.DataBoundItem == ee.subscriber);
if (item != null)
{
listViewSubscribers.BeginUpdate();
Subscriber sub = (item.DataBoundItem as Subscriber);
sub.Favorite = ee.isActive;
sub.NrOfUpdates++;
listViewSubscribers.EndUpdate();
}
//listFavorites.DataSource = subscribersList;
FilterDescriptor valueFilter = new FilterDescriptor("Favorite", FilterOperator.IsEqualTo, (Boolean)true);
listFavorites.FilterDescriptors.Clear();
listFavorites.FilterDescriptors.Add(valueFilter);
};
((SubscriberVisualListItem)e.VisualItem).OnTextSend_Req += delegate (object s, SubscriberVisualListItem.TextSendEventArgs ee)
{
//Utils.WriteLine("Text is " + ee.subscriber.DispatcherName + " | " + ee.text);
//String Totrans = "#142#" + ee.subscriber.Gw_and_radioID + "." + ee.subscriber.Imei + "#" + ee.text + "#" + (int)DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime()) + "#";
//String Totrans = "#142#" + ee.subscriber.Gw_and_radioID + "." + ee.subscriber.Imei + "#" + ee.text + "#" + (int)DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime()) + "#" +
// MainForm2.userIDX + "#";
////((MainForm2)(this.Parent)).Send_UDP_cmd(Totrans, 0, 0);
//mainparent.Send_UDP_cmd(Totrans, 0, 0);
//mainparent.DisplayToast(MainForm2.returnLNGString("txtMsgTo") + ee.subscriber.DispatcherName, string.Format(MainForm2.returnLNGString("msgHTML"), ee.text));
mainparent.SendSmsOnMBus(ee.text, ee.subscriber.Sc_id, (int)DateTime.Now.ToUniversalTime().DateTo70Format());
};
((SubscriberVisualListItem)e.VisualItem).OnRemote_Click += delegate (object s, SubscriberVisualListItem.ToggleClickEventArgs ee)
{
// Utils.WriteLine("Remote is " + ee.subscriber.DispatcherName + " | " + ee.isActive);
sendRemoteMOnitor(ee.subscriber);
mainparent.DisplayToast(MainForm2.returnLNGString("Remotemonitorfor") + " " + ee.subscriber.DispatcherName, MainForm2.returnLNGString("remoteMonitorHTML"));
};
}
}
private void listFavorites_VisualItemFormatting(object sender, ListViewVisualItemEventArgs e)
{
// write the gateway name to the topRight element
if (e.VisualItem is SubscriberVisualListItem && e.VisualItem.Data.DataBoundItem is Subscriber)
(e.VisualItem as SubscriberVisualListItem).topRightElement.Text = (e.VisualItem.Data.DataBoundItem as Subscriber).GatewayName;
if (e.VisualItem.Selected)
{
e.VisualItem.DrawFill = true;
e.VisualItem.BackColor = MainForm2.GridSelectedRow;
e.VisualItem.NumberOfColors = 1;
}
else
e.VisualItem.DrawFill = false;
}
private void rlvGatewayStatus_VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e)
{
if (e.VisualItem is IconListViewVisualItem)
{
e.VisualItem = new RadioGatewayStatusVisualItem();
}
}
private void rlvGatewayStatus_VisualItemFormatting(object sender, ListViewVisualItemEventArgs e)
{
if (e.VisualItem.Selected)
{
e.VisualItem.DrawFill = false;
e.VisualItem.BackColor = MainForm2.GridSelectedRow;
e.VisualItem.NumberOfColors = 1;
}
else
e.VisualItem.DrawFill = false;
}
#endregion
/// <summary>
/// Change fore color and background color for the export button when its state changes
/// </summary>
private void btRecordingsList_EnabledChanged(object sender, EventArgs e)
{
if (btRecordingsList.Enabled)
{
btRecordingsList.ButtonElement.ButtonFillElement.BackColor = Color.White;
btRecordingsList.ButtonElement.TextElement.ForeColor = MainForm2.ButtonColor;
}
else
{
btRecordingsList.ButtonElement.ButtonFillElement.BackColor = Color.WhiteSmoke;
btRecordingsList.ButtonElement.TextElement.ForeColor = Color.Gray;
}
}
/// <summary>
/// Handles the picture box click for simulating a checkbox and to
/// enable/disable other panels
/// </summary>
private Image themeUnit_Image = Utils.ChangeColor(Dispatcher.Properties.Resources.filter_user_black, MainForm2.ButtonColor);
private Image themeCallType_Image = Utils.ChangeColor(Dispatcher.Properties.Resources.filter_type_black, MainForm2.ButtonColor);
private Image theme24H_Image = Utils.ChangeColor(Dispatcher.Properties.Resources.h_24h, MainForm2.ButtonColor);
private Image themePlay_Image = Utils.ChangeColor(Dispatcher.Properties.Resources.r_play, MainForm2.ButtonColor);
private void pbEnableDisable_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbUnit)
{
if (pbUnit.Tag.Equals("disabled"))
{
pbUnit.Tag = "enabled";
pbUnit.Image = themeUnit_Image;
rcbUnit.Enabled = true;
ckUnit.Checked = true;
}
else
{
pbUnit.Tag = "disabled";
pbUnit.Image = Dispatcher.Properties.Resources.filter_user_grey;
rcbUnit.Enabled = false;
ckUnit.Checked = false;
}
// force the remove of the filters
rcbUnit_ItemCheckedChanged(rcbCallType, null);
}
else if ((PictureBox)sender == pbCallType)
{
if (pbCallType.Tag.Equals("disabled"))
{
pbCallType.Tag = "enabled";
pbCallType.Image = themeCallType_Image;
rcbCallType.Enabled = true;
ckCallType.Checked = true;
}
else
{
pbCallType.Tag = "disabled";
pbCallType.Image = Dispatcher.Properties.Resources.filter_type_grey;
rcbCallType.Enabled = false;
ckCallType.Checked = false;
}
// force the remove of the filters
rcbCallType_ItemCheckedChanged(rcbCallType, null);
}
else if ((PictureBox)sender == pb24H)
{
if (pb24H.Tag.Equals("enabled"))
{
pb24H.Tag = "disabled";
rdpEndTime.Enabled = true;
rdpStartTime.Enabled = true;
pb24H.Image = global::Dispatcher.Properties.Resources.h_24h_w;
}
else if (pb24H.Tag.Equals("disabled"))
{
pb24H.Tag = "enabled";
rdpEndTime.Enabled = false;
rdpStartTime.Enabled = false;
pb24H.Image = theme24H_Image;
}
// filter the grid for 24 hours or not
TimeFilter(pb24H.Tag.Equals("enabled"));
}
}
/// <summary>
/// filter recordings based on the selected units
/// </summary>
private void rcbUnit_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
// clear all units filters
gridRecordings.FilterDescriptors.Remove("From");
gridRecordings.FilterDescriptors.Remove("To");
// do not add filter if the filter is not active
if (!rcbUnit.Enabled)
{
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
return;
}
// add filters only if selected unit
if (rcbUnit.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
List<String> selectedItems = new List<string>();
// for each selected unit add a custom filedescriptor
foreach (RadListDataItem item in rcbUnit.CheckedItems)
{
selectedItems.Add(item.Text.ToString());
}
// add filter
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
for (int i = 0; i < selectedItems.Count; i++)
{
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("From", FilterOperator.Contains, selectedItems[i]));
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("To", FilterOperator.Contains, selectedItems[i]));
}
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
this.gridRecordings.FilterDescriptors.Add(statusDescriptor);
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
}
}
/// <summary>
/// filter recordings based on the selected call types
/// </summary>
private void rcbCallType_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
try
{
// clear all call types filters
gridRecordings.FilterDescriptors.Remove("CallTypeDirectionFilter");
// do not add filters if the picture box is inactive
if (!rcbCallType.Enabled)
{
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
return;
}
// add filters only if selected call type
if (rcbCallType.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
String[] types = new String[rcbCallType.CheckedItems.Count];
int i = 0;
// for each selected unit add a custom filedescriptor
foreach (RadListDataItem item in rcbCallType.CheckedItems)
{
types[i++] = item.Text;
//statusDescriptor.FilterDescriptors.Add();
}
// add filter
this.gridRecordings.FilterDescriptors.Add(new FilterDescriptor("CallTypeDirectionFilter", FilterOperator.IsContainedIn, types));
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
}
}
catch (Exception ex)
{
Utils.WriteLine("rcbCallType_ItemCheckedChanged : " + ex.ToString(),
ConsoleColor.Red);
}
}
private void btRecordingsList_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Docx|*.docx";
sfd.Title = "Save all filtered recordings";
string dateTime = DateTime.Now.ToString();
dateTime = dateTime.Replace("/", "_");
dateTime = dateTime.Replace("\\", "_");
dateTime = dateTime.Replace(" ", "_");
dateTime = dateTime.Replace(":", ".");
sfd.FileName = String.Format(@"" + (MainForm2.radioType == RADIOTYPE.SIMOCO ? "Simoco" : MainForm2.radioType == RADIOTYPE.EXCERA ? "Excera" : "SafeMobile")
+ "_recordings_{0}.docx", dateTime);
DialogResult dr = sfd.ShowDialog();
// If the file name is not an empty string open it for saving.
if (dr == System.Windows.Forms.DialogResult.OK
|| dr == System.Windows.Forms.DialogResult.Yes)
{
// We will need a file name for our output file (change to suit your machine):
string fileNameTemplate = sfd.FileName + (sfd.FileName.EndsWith(".docx") ? "" : ".docx"); //@"Invoice_{0}-{1:MM_dd_yy_HH.mm.ss}.docx";
// Let's save the file with a meaningful name, including the applicant name and the letter date:
//System.IO.Directory.CreateDirectory("exports");
//string outputFileName = string.Format("exports/" + fileNameTemplate, cbCabinetWork.Text, DateTime.Now);
// Grab a reference to the desired template
var doc = Novacode.DocX.Load(@"resource\templates\export_recordings.docx");
doc.ReplaceText("%DATA%", String.Format("{0}", DateTime.Now.ToString()));
doc.ReplaceText("%COMPANY%", "Generated using " + (MainForm2.radioType == RADIOTYPE.SIMOCO ? "Simoco" : MainForm2.radioType == RADIOTYPE.EXCERA ? "Excera" : "SafeMobile")
+ " Dispatch");
#region Works
// get the empty template row
Novacode.Row emptyRow = doc.Tables[0].Rows[doc.Tables[0].RowCount - 1];
FontFamily centuryGothic = null;
try
{
centuryGothic = new FontFamily("Century Gothic");
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
FontFamily font = new FontFamily("Arial");
if (centuryGothic != null)
font = centuryGothic;
int counter = 1;
//Utils.WriteLine(gridRecordings.ChildRows.Count + "");
foreach (GridViewRowInfo groupRow in gridRecordings.ChildRows)
{
if (groupRow.ChildRows.Count > 0)
{
foreach (GridViewRowInfo gridRow in groupRow.ChildRows)
{
Recording rec = gridRow.DataBoundItem as Recording;
// skip group headers and others UI elements withoug databound items
if (rec == null)
continue;
// add a new empty row and then edit it
doc.Tables[0].InsertRow(emptyRow);
// get the new inserted row which is empty
Novacode.Row row = doc.Tables[0].Rows[doc.Tables[0].RowCount - 1];
int column = 0;
row.Cells[column++].Paragraphs[0].Append(counter++ + "").FontSize(9).Font(font);
using (MemoryStream ms = new MemoryStream())
{
//write image to the memory stream
Utils.ScaleImage(rec.callTypeImage, 48, 48).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// go to the begining of the picture
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = doc.AddImage(ms); // Create image.
Novacode.Picture pic1 = img.CreatePicture(); // Create picture.
row.Cells[column++].Paragraphs[0].AppendPicture(pic1);
}
row.Cells[column++].Paragraphs[0].Append(rec.username).FontSize(9).Font(font);
row.Cells[column - 1].Paragraphs[0].Color(Color.FromArgb(0, 0, 255));
row.Cells[column - 1].Paragraphs[0].Bold();
row.Cells[column++].Paragraphs[0].Append(rec.From).FontSize(9).Font(font);
row.Cells[column++].Paragraphs[0].Append(rec.To).FontSize(9).Font(font);
row.Cells[column++].Paragraphs[0].Append(rec.DateTimeStart.ToString("dd.MM.yyyy HH:mm:ss")).FontSize(8).Font(font);
row.Cells[column++].Paragraphs[0].Append(rec.duration + " sec").FontSize(9).Font(font);
row.Cells[column - 1].Paragraphs[0].Color(Color.FromArgb(66, 66, 66));
}
}
}
// remove first row after the header because is an empty one
doc.Tables[0].RemoveRow(1);
#endregion
// Save as New filename:
doc.SaveAs(sfd.FileName);
// Open in word:
//Process.Start("WINWORD.EXE", "\"" + outputFileName + "\"");
mainparent.DisplayToast(MainForm2.returnLNGString("recExpSucces"),
string.Format(MainForm2.returnLNGString("RadioExportHTML"), fileNameTemplate, sfd.FileName));
}
}
private void LoadRecordingTimer_Tick(object sender, EventArgs e)
{
LoadRecordingTimer.Stop();
LoadRecordingTimer.Enabled = false;
}
private void LoadSubscriberTimer_Tick(object sender, EventArgs e)
{
LoadSubscriberTimer.Stop();
LoadSubscriberTimer.Enabled = false;
//listViewSubscribers.DataSource = null;
//Populate_subscriber_list();
//listSubscribers.DataSource = subscribersList;
}
private void listFavorites_SelectedItemChanged(object sender, EventArgs e)
{
}
#region AUDIO SETTINGS MIC & HEADSET
private NAudio.Wave.WaveIn waveIn = null;
private NAudio.Wave.WaveOut waveOut = null;
private Stream stream = Dispatcher.Properties.Resources.air;
private Boolean isPlaying = false;
private static MMDeviceEnumerator enumer = new MMDeviceEnumerator();
private MMDevice headsetDevice = null;
/// <summary>
/// Save the new REc Sound card into the Database
/// </summary>
private void InputSoundList_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
try
{
if (waveIn != null)
{
waveIn.StopRecording();
waveIn = null;
}
}
catch (NAudio.MmException ex)
{
Utils.WriteLine("InputSoundList_SelectedIndexChanged 1 Exception: " + ex.ToString(), ConsoleColor.Red);
}
try
{
waveIn = new NAudio.Wave.WaveIn();
waveIn.DeviceNumber = e.Position;
waveIn.DataAvailable += waveIn_DataAvailable;
int sampleRate = voicemanager_sampleRate; // 8 kHz
int channels = 1; // mono
waveIn.WaveFormat = new NAudio.Wave.WaveFormat(sampleRate, channels);
waveIn.StartRecording();
}
catch (NAudio.MmException ex)
{
Utils.WriteLine("InputSoundList_SelectedIndexChanged 2 Exception: " + ex.ToString(), ConsoleColor.Red);
}
}
/// <summary>
/// Evalute the sound received from the input device
/// </summary>
void waveIn_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
int count = 0;
float min = 0, max = 0;
for (int index = 0; index < e.BytesRecorded; index += 2)
{
short sample = (short)((e.Buffer[index + 1] << 8) |
e.Buffer[index + 0]);
float sample32 = sample / 32768f;
// initialize the min and max
if (index == 0)
{
min = sample32;
max = sample32;
}
if (max < sample32)
max = sample32;
if (min > sample32)
min = sample32;
float m = Math.Max(max, Math.Abs(min));
//if (count++ % 10 == 0)
// Console.WriteLine(m + " | " + Math.Log10(m));
//Console.WriteLine("Val: " + Math.Max(max, Math.Abs(min)) * 20);
if (count % 100 == 0)
{
if (m < 0.003)
m = 0.001f;
//rtbMicrophoneVolume.Value = (float)((Math.Log10(m) + 3) * 33);
rtbMicrophoneVolume.Value = (int)(Math.Max(max, Math.Abs(min)) * 100);
}
}
}
/// <summary>
/// Detach from previous mic that was listened in order to check it's levels
/// </summary>
private void InputSoundList_SelectedIndexChanging(object sender, Telerik.WinControls.UI.Data.PositionChangingCancelEventArgs e)
{
if (waveIn != null)
waveIn.DataAvailable -= waveIn_DataAvailable;
}
/// <summary>
/// I don't have where to call this
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (waveIn != null)
{
waveIn.StopRecording();
waveIn = null;
}
}
/// <summary>
/// Save the new Play Sound card into the Database
/// </summary>
private void OutputSoundList_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
}
/// <summary>
/// Event listener for when the audio volume changes
/// </summary>
/// <param name="data"></param>
void AudioEndpointVolume_OnVolumeNotification(AudioVolumeNotificationData data)
{
try
{
// This shows data.MasterVolume, you can do whatever you want here
Utils.WriteLine("Volume level is : " + data.MasterVolume * 100f, ConsoleColor.Red);
//rtbSpeakersVolume.Value = data.MasterVolume * 100f;
}
catch (Exception e)
{
Utils.WriteLine("AudioEndpointVolume_OnVolumeNotification: " + e.ToString(), ConsoleColor.Red);
}
}
/// <summary>
/// Reset audio stream when the playback has finished
/// </summary>
void waveOut_PlaybackStopped(object sender, EventArgs e)
{
//Utils.WriteLine("Done playing");
stream.Position = 0;
pbPlayTestSound.Image = themePlay_Image;
isPlaying = false;
}
/// <summary>
/// Detach from previous sound output device in order to attach to another
/// </summary>
private void OutputSoundList_SelectedIndexChanging(object sender, Telerik.WinControls.UI.Data.PositionChangingCancelEventArgs e)
{
// close previous sounds
if (waveOut != null)
{
pbPlayTestSound.Image = themePlay_Image;
isPlaying = false;
waveOut.PlaybackStopped -= waveOut_PlaybackStopped;
waveOut.Pause();
waveOut.Stop();
waveOut = null;
stream.Position = 0;
}
//if (OutputSoundList.SelectedItem != null && OutputSoundList.SelectedItem.DataBoundItem != null)
//{
// KeyValuePair<Int16, Tuple<String, MMDevice>> dataBound =
// (KeyValuePair<Int16, Tuple<String, MMDevice>>)OutputSoundList.SelectedItem.DataBoundItem;
// OutputSoundList.Text = dataBound.Value.Item2.FriendlyName + " - " + dataBound.Value.Item2.DeviceFriendlyName;
//}
}
/// <summary>
/// Format the text which will be displayed inside the heasphone dropdown list
/// </summary>
private void OutputSoundList_VisualListItemFormatting(object sender, VisualItemFormattingEventArgs args)
{
//KeyValuePair<Int16, Tuple<String, MMDevice>> dataBound =
// (KeyValuePair<Int16, Tuple<String, MMDevice>>)args.VisualItem.Data.DataBoundItem;
//args.VisualItem.Text = dataBound.Value.Item2.FriendlyName + " - " + dataBound.Value.Item2.DeviceFriendlyName;
//args.VisualItem.Text = ((RadDropDownList)sender).SelectedItem.Text;
}
/// <summary>
/// Save the new audio configuration into the database and
/// reset it into radio tab
/// </summary>
private void rbApplyAudioConfiguration_Click(object sender, EventArgs e)
{
//KeyValuePair<Int16, Tuple<String, MMDevice>> dataBound =
// (KeyValuePair<Int16, Tuple<String, MMDevice>>)OutputSoundList.SelectedItem.DataBoundItem;
//smdbObj.SaveSoundCardinDB(0, dataBound.Value.Item1, InputSoundList.Text, "");
smdbObj.SaveSoundCardinDB(0, OutputSoundList.Text, InputSoundList.Text, "");
// set the new index values
selectedINDevice = InputSoundList.SelectedIndex;
//selectedOUTDevice = ((KeyValuePair<Int16, Tuple<String, MMDevice>>)OutputSoundList.SelectedItem.DataBoundItem).Key;
selectedOUTDevice = OutputSoundList.SelectedIndex;
StartnVoice();
mainparent.DisplayToast(MainForm2.returnLNGString("Audiosettingschangedsuccessfully"),
string.Format(MainForm2.returnLNGString("newAudioCfg"), InputSoundList.Text, OutputSoundList.Text));
}
/// <summary>
/// Play a sound on the selected configuration in order to test the current
/// selected audio device
/// </summary>
private void pbPlayTestSound_Click(object sender, EventArgs e)
{
try
{
if (!isPlaying)
{
pbPlayTestSound.Image = Dispatcher.Properties.Resources.r_play_blue;
// load the stream
NAudio.Wave.WaveFileReader waveReader = new NAudio.Wave.WaveFileReader(stream);
// create a new output device based on the selected device
waveOut = new NAudio.Wave.WaveOut();
//KeyValuePair<Int16, Tuple<String, MMDevice>> dataBound =
// (KeyValuePair<Int16, Tuple<String, MMDevice>>)OutputSoundList.SelectedItem.DataBoundItem;
//Utils.WriteLine("Playing on " + dataBound.Key + " device");
//waveOut.DeviceNumber = dataBound.Key;
Utils.WriteLine("Playing on " + OutputSoundList.SelectedItem.Text + " device");
waveOut.DeviceNumber = OutputSoundList.SelectedIndex;
// initialize the output device
waveOut.Init(waveReader);
// detech when the play had finished to reset the stream to 0
waveOut.PlaybackStopped += waveOut_PlaybackStopped;
// flag that playing
isPlaying = true;
// play sound
waveOut.Play();
}
}
catch (Exception ex)
{
Utils.WriteLine("Can't play sound : " + ex.ToString());
}
}
#endregion
#region STYLE GRID RECORDINGS
/// <summary>
/// Set the event listener for the play click
/// </summary>
private void gridRecordings_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
{
GridCellElement cellElement = e.CellElement;
GridViewDataColumn columnInfo = e.CellElement.ColumnInfo as GridViewDataColumn;
// do not draw border
cellElement.DrawBorder = false;
// do not highlight the cell on which was clicked
if (e.CellElement.IsCurrent)
e.CellElement.IsCurrent = false;
// set padding and force the content adding
if (cellElement is RecordingGridCellElement && columnInfo.Name == "recording")
{
cellElement.Padding = new Padding(0, 0, 0, 0);
//cellElement.SetContent();
// add click listener only if not added before
if ((cellElement.Tag != null && !cellElement.Tag.Equals("done")) || cellElement.Tag == null)
{
((RecordingGridCellElement)cellElement).OnPlay_Click += delegate (object s, RecordingGridCellElement.ToggleClickEventArgs ee)
{
// Utils.WriteLine("Fav is " + ee.recording.username + " | " + ee.isActive);
PlayFile(ee.recording.RecID, ee.recording.duration);
};
}
cellElement.Tag = "done";
}
}
/// <summary>
/// Prevent the opening of the context menu
/// </summary>
private void gridRecordings_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
{
e.Cancel = true;
}
/// <summary>
/// Set the type of data which will be displayed inside the grid
/// </summary>
private void gridRecordings_CreateCell(object sender, GridViewCreateCellEventArgs e)
{
// format live column
if (e.Row is GridDataRowElement)
{
// increase row height
//e.Row.RowInfo.Height = 53;
if (e.Column.Name.Equals("recording"))
{
e.CellType = typeof(RecordingGridColumn);
e.CellElement = new RecordingGridCellElement(e.Column, e.Row);
}
if (e.Column is GridViewIndentColumn)
{
e.Column.IsVisible = false;
/*
e.Column.MaxWidth = 7;
e.Column.MinWidth = 7;
e.Column.Width = 7;*/
//e.CellElement.Visibility = ElementVisibility.Hidden;
}
}
}
private void gridRecordings_CustomGrouping(object sender, GridViewCustomGroupingEventArgs e)
{
}
private void gridRecordings_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e)
{
if (e.SummaryItem == null || e.Value == null)
return;
try
{
if (e.SummaryItem.Name.Equals("DateStart"))
{
if (((DateTime)e.Value).Year == DateTime.Now.Year)
e.FormatString = ((DateTime)e.Value).ToString("dd.MMMM");
else
e.FormatString = ((DateTime)e.Value).ToString("dd.MMMM.yyyy");
}
else if (e.SummaryItem.Name.Equals("callType"))
{
e.FormatString = e.Value.ToString().Replace('_', ' ');
}
else if (e.SummaryItem.Name.Equals("Initial"))
{
e.FormatString = e.Value.ToString().ToUpper();
}
else if (e.SummaryItem.Name.Equals("callDirection"))
{
e.FormatString = e.Value.ToString();
}
}
catch (Exception ex)
{
Utils.WriteLine("gridRecordings_GroupSummaryEvaluate: " + ex.ToString(), ConsoleColor.Red);
}
}
#endregion
#region FILTERS
/// <summary>
/// Intercept date time change in order to filter the recordings grid
/// </summary>
private void TimeFilter_ValueChanged(object sender, EventArgs e)
{
TimeFilter(false);
}
/// <summary>
/// Filter recordings grid for displaying the last 24 hours
/// or the selected interval from the date time
/// </summary>
/// <param name="is24Hours">Boolean telling if the last 24 hours
/// are needed</param>
private void TimeFilter(bool is24Hours)
{
// clear all units filters
gridRecordings.FilterDescriptors.Remove("DateTimeStart");
gridRecordings.FilterDescriptors.Remove("DateTimeEnd");
// Create a composite file descriptor with AND logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.And;
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("DateTimeStart", FilterOperator.IsGreaterThan,
pb24H.Tag.Equals("enabled") ? (DateTime.Now).AddDays(-1) : rdpStartTime.Value));
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("DateTimeEnd", FilterOperator.IsLessThan,
pb24H.Tag.Equals("enabled") ? DateTime.Now : rdpEndTime.Value));
// add filter
this.gridRecordings.FilterDescriptors.Add(statusDescriptor);
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
}
/// <summary>
/// Format the rows to display alternate colors
/// </summary>
private void gridRecordings_RowFormatting(object sender, RowFormattingEventArgs e)
{
e.RowElement.DrawFill = true;
e.RowElement.NumberOfColors = 1;
if (e.RowElement.IsSelected)
e.RowElement.BackColor = MainForm2.GridSelectedRow;
else
e.RowElement.BackColor = (e.RowElement.RowInfo.Index % 2 == 0 ? Color.White : MainForm2.GridAlternateRow);
}
/// <summary>
/// Invalidate selected row in order for the play button to be placed
/// on the grid
/// </summary>
private void gridRecordings_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
{
if (e.CurrentRow == null)
return;
e.CurrentRow.InvalidateRow();
}
/// <summary>
/// Scroll to first row after the filtering is done
/// </summary>
private void gridRecordings_FilterChanged(object sender, GridViewCollectionChangedEventArgs e)
{
if (gridRecordings.Rows.Count > 0)
{
gridRecordings.Rows[0].IsSelected = true;
gridRecordings.Rows[0].IsCurrent = true;
gridRecordings.CurrentRow = gridRecordings.Rows[0];
gridRecordings.TableElement.ScrollToRow(gridRecordings.CurrentRow);
}
}
/// <summary>
/// Display the tooltip when the mouse enters over the
/// picture box
/// </summary>
private void pbFilter_MouseEnter(object sender, EventArgs e)
{
PictureBox pbSender = (PictureBox)sender;
String toolTipTitle = "";
String toolTipText = "";
if (pbSender == pbFilterTime)
{
toolTipTitle = MainForm2.returnLNGString("Recordingtimegrouping");
toolTipText = MainForm2.returnLNGString("RecordingtimegroupingDET");
}
else if (pbSender == pbFilterDirection)
{
toolTipTitle = MainForm2.returnLNGString("Recordingdirectiongrouping");
toolTipText = MainForm2.returnLNGString("RecordingdirectiongroupingDET");
}
else if (pbSender == pbFilterType)
{
toolTipTitle = MainForm2.returnLNGString("Recordingcalltypegrouping");
toolTipText = MainForm2.returnLNGString("RecordingcalltypegroupingDET");
}
else if (pbSender == pbFilterUser)
{
toolTipTitle = MainForm2.returnLNGString("Recordinguserinitialsgrouping");
toolTipText = MainForm2.returnLNGString("RecordinguserinitialsgroupingDET");
}
else if (pbSender == pb24H)
{
toolTipTitle = MainForm2.returnLNGString("Filterrecordingsbytime");
toolTipText = MainForm2.returnLNGString("FilterrecordingsbytimeDET");
}
else if (pbSender == pbCallType)
{
toolTipTitle = MainForm2.returnLNGString("Filterrecordingsbycalltype");
toolTipText = MainForm2.returnLNGString("FilterrecordingsbycalltypeDET");
}
else if (pbSender == pbUnit)
{
toolTipTitle = MainForm2.returnLNGString("Filterrecordingsbyuser");
toolTipText = MainForm2.returnLNGString("FilterrecordingsbyuserDET");
}
toolTipHelp.ToolTipTitle = toolTipTitle + ": " + (pbSender.Tag.Equals("enabled") ? MainForm2.returnLNGString("active") : MainForm2.returnLNGString("inactive"));
toolTipHelp.Show(
String.Format(toolTipText), pbSender, 150000);
}
/// <summary>
/// Hide the tooltip when the mouse exits the picture box
/// </summary>
private void pbFilter_MouseLeave(object sender, EventArgs e)
{
toolTipHelp.Hide((PictureBox)sender);
}
/// <summary>
/// Display a message inside the recordings grid based on its state
/// If the list of recordings has no visible row, but has rows, a message
/// telling that the current configuration of filters has no recordings
/// </summary>
private void DisplayEmptyMessageOnRecordingsGrid()
{
// display a message for when the table elements are empty
if (gridRecordings.ChildRows.Count > 0)
gridRecordings.TableElement.Text = "";
// recordings exists but outside the filters
else if (gridRecordings.ChildRows.Count == 0 && gridRecordings.Rows.Count > 0)
{
gridRecordings.TableElement.Text = MainForm2.returnLNGString("norecordstoshow");
}
// no recordings at all
else
gridRecordings.TableElement.Text = MainForm2.returnLNGString("listOfRecordings");
}
#endregion
private void listBoxRadioGateways_ItemDataBound(object sender, ListItemDataBoundEventArgs args)
{
RadioGateway view = (RadioGateway)args.NewItem.DataBoundItem;
args.NewItem.Text = "<html>" +
"<b>" + view.Name + "</b>" +
"<br>" + "<i>" +
" " + view.TypeDesc + "</i>";
args.NewItem.Image = global::Dispatcher.Properties.Resources.red_status;
}
private void listBoxRadioGateways_CreatingVisualListItem(object sender, CreatingVisualListItemEventArgs args)
{
RadListVisualItem visualItem = new RadListVisualItem();
visualItem.Padding = new Padding(5, 5, 0, 5);
args.VisualItem = visualItem;
}
private void timer1_Tick(object sender, EventArgs e)
{
lbCurrentDateTime.Text = DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
}
private void RearrangeCallForm()
{
//CallsForm.position = 0;
//foreach (KeyValuePair<string, CallsForm> callForm in callFormContainer)
//{
// if (callForm.Value != null)
// {
// callForm.Value.Location = new Point(Screen.PrimaryScreen.Bounds.X + 93, //should be (0,0)
// Screen.PrimaryScreen.Bounds.Y + CallsForm.position);
// callForm.Value.TopMost = true;
// callForm.Value.StartPosition = FormStartPosition.Manual;
// CallsForm.position += 93;
// }
//}
}
private void GetAvailablePosition()
{
List<string> positionList = new List<string>();
int deviation = 310; // 304 latimea butonului de ptt deci 310 sa nu il imbarlige
CallsForm.positionX = 0;
CallsForm.positionY = 0;
foreach (KeyValuePair<string, CallsForm> callForm in callFormContainer)
{
if (callForm.Value != null)
{
positionList.Add(string.Format("({0},{1})", callForm.Value.Location.Y, callForm.Value.Location.X));
}
}
for (int j = 0; j <= this.Width / 350; j++)
{
for (int i = 0; i <= this.Height / 94; i++)
{
int pointY = i * 94;
int pointX = j * 350 + deviation;
string point = string.Format("({0},{1})", pointY, pointX);
if (!positionList.Contains(point))
{
CallsForm.positionY = pointY;
CallsForm.positionX = pointX;
return;
}
}
}
}
private class Gatewaymulticast
{
private string gatewayIp = "";
private UdpMulticast udp4Voice2;
private RadioTab parent;
public Gatewaymulticast(string GatewayIp, int voicePort, RadioTab parent)
{
gatewayIp = GatewayIp;
this.parent = parent;
udp4Voice2 = new UdpMulticast(gatewayIp, voicePort);
udp4Voice2.OnNewDataRecv += Udp4Voice2_OnNewDataRecv;
udp4Voice2.StartListen(MainForm2.cfg.LocalIP);
}
private void Udp4Voice2_OnNewDataRecv(byte[] data, int dataLen)
{
try
{
//Console.WriteLine("Recived AudioData RecivedData:" + RecivedData + " dataLen:" + dataLen);
if ((parent.RecivedData) && (dataLen > 30))//&& (VoiceON)
{
//int activeCount = ShapeNew.receiving_hash.Count;
//if (MainForm2.PriorityIP.Length == 0) MainForm2.PriorityIP = gatewayIp;
if (MainForm2.PriorityIP.CompareTo(gatewayIp) == 0)
{
if (parent.buffWaveProvider != null)
parent.buffWaveProvider.AddSamples(data, 0, dataLen);
//nVOice.PlaySound(data, dataLen);
}
}
}
catch (Exception ex)
{
SM.Debug("Error on put data: " + ex.ToString());
}
}
}
#region call patching
private void gvPatch_ValueChanged(object sender, EventArgs e)
{
if (((GridVirtualizedCellElement)(((RadDropDownListEditor)sender).OwnerElement)).Data.HeaderText != "Type")
return;
if (((RadDropDownListEditor)sender).Value.ToString() == "Dispatcher")
{
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DataSource = dispatchers;
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DisplayMember = "UserName";
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DataSource = dispatchers;
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DisplayMember = "UserName";
}
if (((RadDropDownListEditor)sender).Value.ToString() == "Gateway")
{
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DataSource = radiogateways;
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DisplayMember = "Name";
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DataSource = radiogateways;
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DisplayMember = "Name";
}
}
private void gvPatch_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
{
try
{
if (gvPatch == null)
return;
if (gvPatch.CurrentRow.Cells["type"].Value == null)
return;
if (gvPatch.CurrentRow.Cells["type"].Value.ToString() == "Dispatcher")
{
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DataSource = dispatchers;
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DisplayMember = "UserName";
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DataSource = dispatchers;
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DisplayMember = "UserName";
}
if (gvPatch.CurrentRow.Cells["type"].Value.ToString() == "Gateway")
{
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DataSource = radiogateways;
((GridViewComboBoxColumn)gvPatch.Columns["incoming"]).DisplayMember = "Name";
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DataSource = radiogateways;
((GridViewComboBoxColumn)gvPatch.Columns["outgoing"]).DisplayMember = "Name";
}
}
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
}
private void gvPatch_UserAddingRow(object sender, GridViewRowCancelEventArgs e)
{
try
{
if ((gvPatch.CurrentRow.Cells["incoming"]).Value == null || (gvPatch.CurrentRow.Cells["outgoing"]).Value == null)
{
e.Rows[0].ErrorText = MainForm2.returnLNGString("incOutNotNull");
e.Cancel = true;
return;
}
//check if incoming = outgoing or if this row is already added
string type = (gvPatch.CurrentRow.Cells["type"]).Value.ToString();
string incoming = (gvPatch.CurrentRow.Cells["incoming"]).Value.ToString();
string outgoing = (gvPatch.CurrentRow.Cells["outgoing"]).Value.ToString();
string incomingId = "";
string outgoingId = "";
int tip = 0;
if (type == "Dispatcher")
{
incomingId = dispatchers.First(s => s.UserName == incoming).Id.ToString();
outgoingId = dispatchers.First(s => s.UserName == outgoing).Id.ToString();
tip = 0;
}
else if (type == "Gateway")
{
RadioGateway incomingGW = radiogateways.First(s => s.Name == incoming);
RadioGateway outgoingGW = radiogateways.First(s => s.Name == outgoing);
incomingId = incomingGW.Gw_id + "." + incomingGW.Id;
outgoingId = outgoingGW.Gw_id + "." + outgoingGW.Id;
tip = 1;
}
else
{
e.Cancel = true;
return;
}
string concat = type + incoming + outgoing;
if (incoming == outgoing)
{
e.Rows[0].ErrorText = MainForm2.returnLNGString("incOutEqError");
e.Cancel = true;
return;
}
if (patchList.Contains(concat))
{
e.Rows[0].ErrorText = MainForm2.returnLNGString("callPatchAlready");
e.Cancel = true;
return;
}
string key = type + "." + incomingId;
if (!patchDictionary.ContainsKey(key))
{
patchDictionary.Add(key, new List<string>());
}
if (patchDictionary.ContainsKey(key))
{
if (!patchDictionary[key].Contains(outgoingId))
patchDictionary[key].Add(outgoingId);
}
//updatePatchStatus(incoming, true);
updatePatchStatus(outgoing, true, type);
patchList.Add(concat);
//send data to message bus
string Totrans = "#510#" + tip + "#" + incomingId + "#" + incoming + "#" + outgoingId + "#" + outgoing + "#" + MainForm2.userIDX;
parent.Send_UDP_cmd(Totrans, 0, 0);
e.Rows[0].ErrorText = string.Empty;
}
catch(Exception ex)
{
e.Rows[0].ErrorText = ex.Message.ToString();
e.Cancel = true;
}
}
private void gvPatch_UserDeletingRow(object sender, GridViewRowCancelEventArgs e)
{
try
{
string type = (gvPatch.CurrentRow.Cells["type"]).Value.ToString();
string incoming = (gvPatch.CurrentRow.Cells["incoming"]).Value.ToString();
string outgoing = (gvPatch.CurrentRow.Cells["outgoing"]).Value.ToString();
string incomingId = "";
string outgoingId = "";
int tip = 0;
if (type == "Dispatcher")
{
incomingId = dispatchers.First(s => s.UserName == incoming).Id.ToString();
outgoingId = dispatchers.First(s => s.UserName == outgoing).Id.ToString();
tip = 0;
}
if (type == "Gateway")
{
RadioGateway incomingGW = radiogateways.First(s => s.Name == incoming);
RadioGateway outgoingGW = radiogateways.First(s => s.Name == outgoing);
incomingId = incomingGW.Gw_id + "." + incomingGW.Id;
outgoingId = outgoingGW.Gw_id + "." + outgoingGW.Id;
tip = 1;
}
string concat = type + incoming + outgoing;
string key = type + "." + incomingId;
//updatePatchStatus(incoming, false);
updatePatchStatus(outgoing, false, type);
if (patchList.Contains(concat))
patchList.Remove(concat);
if (patchDictionary.ContainsKey(key))
{
if (patchDictionary[key].Contains(outgoingId))
patchDictionary[key].Remove(outgoingId);
if (patchDictionary[key].Count == 0)
patchDictionary.Remove(key);
//send data to message bus
string Totrans = "#511#" + tip + "#" + incomingId + "#" + incoming + "#" + outgoingId + "#" + outgoing + "#" + MainForm2.userIDX;
parent.Send_UDP_cmd(Totrans, 0, 0);
}
}
catch(Exception ex)
{
Utils.WriteLine("Error on deleting call patch from gridview", ConsoleColor.Red);
}
}
internal void StartCallPatch(string type, string key, string from)
{
Utils.WriteLine("Start call patch", ConsoleColor.Green);
runningPatches.Add(from);
pttIsPressed = false;
if (!patchDictionary.ContainsKey(key))
return;
string Totrans = string.Empty;
foreach (string patch in patchDictionary[key])
{
if (type == "Dispatcher")
{
Totrans = String.Format("#201#{0}#{1}#", patch, "224.20." + from + ".1#1");
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 10000, 201));
mainparent.Send_UDP_cmd(Totrans, 10000, 201, from);
}
if (type == "Gateway")
{
Totrans = String.Format("#101#{0}#{1}#", patch, "224.10." + from + "#1");
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 10000, 101));
mainparent.Send_UDP_cmd(Totrans, 10000, 101);
//if (MainForm2.radioGwHT.ContainsKey(patch))
//{
// ((RadioGateway)MainForm2.radioGwHT[patch]).InPatch = true;
// Utils.WriteLine($"Start call patch on {patch} - {((RadioGateway)MainForm2.radioGwHT[patch]).Name}", ConsoleColor.Green);
//}
//if (MainForm2.radioGwHT.ContainsKey(from))
//{
// ((RadioGateway)MainForm2.radioGwHT[from]).InPatch = true;
// Utils.WriteLine($"Start call patch on {from} - {((RadioGateway)MainForm2.radioGwHT[from]).Name}", ConsoleColor.Green);
//}
}
}
}
private void updatePatchStatus(string patch, bool value, string type)
{
if (type == "Dispatcher") //0 -> dispatcher, 1 -> gateway
return;
if (type == "0")
return;
if (!rgwHTByName.ContainsKey(patch))
return;
string key = ((RadioGateway)rgwHTByName[patch]).Gw_id + "." + ((RadioGateway)rgwHTByName[patch]).Id;
if (MainForm2.radioGwHT.ContainsKey(key))
{
((RadioGateway)MainForm2.radioGwHT[key]).InPatch = value;
}
}
private void EndCallPatch(string type, string key, string from)
{
Utils.WriteLine("End call patch", ConsoleColor.Green);
pttIsPressed = false;
runningPatches.RemoveAll(x => x == from);
if (!patchDictionary.ContainsKey(key))
return;
string Totrans = string.Empty;
foreach (string patch in patchDictionary[key])
{
if (type == "Dispatcher")
{
Totrans = String.Format("#211#{0}#{1}#", patch, "224.20." + from + ".1#1");//selected_Subscriber.IP
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 211));
mainparent.Send_UDP_cmd(Totrans, 3000, 211, from);
}
if (type == "Gateway")
{
Totrans = String.Format("#111#{0}#{1}#", patch, "224.10." + from + "#1");
//WatchList.Add(mainparent.Send_UDP_cmd(Totrans, 3000, 111));
mainparent.Send_UDP_cmd(Totrans, 3000, 111);
//if (MainForm2.radioGwHT.ContainsKey(patch))
//{
// ((RadioGateway)MainForm2.radioGwHT[patch]).InPatch = false;
// Utils.WriteLine($"Stop call patch on {patch} - {((RadioGateway)MainForm2.radioGwHT[patch]).Name}", ConsoleColor.Red);
//}
//if (MainForm2.radioGwHT.ContainsKey(from))
//{
// ((RadioGateway)MainForm2.radioGwHT[from]).InPatch = false;
// Utils.WriteLine($"Stop call patch on {from} - {((RadioGateway)MainForm2.radioGwHT[from]).Name}", ConsoleColor.Red);
//}
}
}
this.Invoke((MethodInvoker)delegate
{
pbSpectrum.Image = Dispatcher.Properties.Resources.r_radial_spectrum_00;
});
}
internal void UpdateCallPatchGridViewInfo(int type, Patch patch)
{
string tip, concat, key;
tip = patch.Type == "0" ? "Dispatcher" : "Gateway";
concat = tip + patch.Incoming + patch.Outgoing;
key = tip + "." + patch.IncomingId;
this.Invoke((Action)(() => {
switch (type)
{
case 510:
if (!patchDictionary.ContainsKey(key))
{
patchDictionary.Add(key, new List<string>());
}
if (patchDictionary.ContainsKey(key))
{
if (!patchDictionary[key].Contains(patch.OutgoingId))
patchDictionary[key].Add(patch.OutgoingId);
}
//updatePatchStatus(patch.Incoming, true);
updatePatchStatus(patch.Outgoing, true, patch.Type);
patchList.Add(concat);
dbPatches.Add(patch);
gvPatch.Rows.Add(tip, patch.Incoming, patch.Outgoing);
break;
case 511:
patchList.Remove(concat);
if (patchDictionary.ContainsKey(key))
{
if (patchDictionary[key].Contains(patch.OutgoingId))
patchDictionary[key].Remove(patch.OutgoingId);
if (patchDictionary[key].Count == 0)
patchDictionary.Remove(key);
//updatePatchStatus(patch.Incoming, false);
updatePatchStatus(patch.Outgoing, false, patch.Type);
}
foreach (var row in gvPatch.Rows)
{
if ((row.Cells["incoming"]).Value.ToString() == patch.Incoming && (row.Cells["outgoing"]).Value.ToString() == patch.Outgoing)
{
gvPatch.Rows.Remove(row);
return;
}
}
break;
}
}));
}
#endregion
/// <summary>
/// Intercept when the selected gateway is changed in order to filter the list subscribers and list favorites
/// </summary>
private void rcbddGateways_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
//Utils.WriteLine("rcbddGateways_ItemCheckedChanged", ConsoleColor.DarkCyan);
// clear all statuses filters
listViewSubscribers.FilterDescriptors.Remove("GatewayName");
// add filters only if selected event types
if (rcbddGateways.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
// for each selected status add a custom filedescroptor
foreach (RadCheckedListDataItem item in rcbddGateways.CheckedItems)
{
RadioGateway radioGw = item.DataBoundItem as RadioGateway;
if (radioGw == null)
continue;
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("GatewayName", FilterOperator.IsEqualTo, radioGw.Name)); //radioGw.Gw_id + "." + radioGw.Id));
}
// add filter
this.listViewSubscribers.FilterDescriptors.Add(statusDescriptor);
}
// clear all statuses filters
listFavorites.FilterDescriptors.Remove("GatewayName");
// add filters only if selected event types
if (rcbddGateways.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
// for each selected status add a custom filedescroptor
foreach (RadCheckedListDataItem item in rcbddGateways.CheckedItems)
{
RadioGateway radioGw = item.DataBoundItem as RadioGateway;
if (radioGw == null)
continue;
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("GatewayName", FilterOperator.IsEqualTo, radioGw.Name)); //radioGw.Gw_id + "." + radioGw.Id));
}
// add filter
this.listFavorites.FilterDescriptors.Add(statusDescriptor);
}
}
private void rcddlRecordingsGateways_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
try
{
// clear all call types filters
gridRecordings.FilterDescriptors.Remove("Gw_and_radioID");
// add filters only if selected call type
if (rcddlRecordingsGateways.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
String[] types = new String[rcddlRecordingsGateways.CheckedItems.Count];
int i = 0;
// for each selected unit add a custom filedescriptor
foreach (RadListDataItem item in rcddlRecordingsGateways.CheckedItems)
{
RadioGateway radioGw = item.DataBoundItem as RadioGateway;
types[i++] = radioGw.Gw_id + "." + radioGw.Id;
//statusDescriptor.FilterDescriptors.Add();
}
// add filter
this.gridRecordings.FilterDescriptors.Add(new FilterDescriptor("Gw_and_radioID", FilterOperator.IsContainedIn, types));
// display/hide the empty message
DisplayEmptyMessageOnRecordingsGrid();
}
}
catch (Exception ex)
{
Utils.WriteLine("rcddlRecordingsGateways_ItemCheckedChanged : " + ex.ToString(),
ConsoleColor.Red);
}
}
}
}