using System;
using System.Collections.Generic;
using System.Text;
using Shared;
using Shared.SimpleControl.Pad;
using Shared.SimpleControl.R;
using SmartHome.UI.SimpleControl.Pad.Music;
using System.Xml;
using System.Security;
using SmartHome;
namespace Shared.SimpleControl.Pad.Music
{
class PlayerPage : FrameLayout
{
public override void RemoveFromParent ()
{
base.RemoveFromParent ();
clearA31Threads ();
clearOldThreads ();
}
///
/// 播放界面
///
FrameLayout PalyMusicPage;
///
/// 源界面
///
FrameLayout MusicSourcePage;
///
/// 所有音乐播放器的音量
///
HorizontalSeekBar allVol;
///
/// 静音
///
Button muteVol;
///
/// 加载所有音乐的滑动视图
///
MusicVerticalScrolViewLayout verticalScrolViewLayout;
string openWeb (string url)
{
try {
Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient (3000);
return System.Text.Encoding.UTF8.GetString (webClient.DownloadData (url));
} catch {
return null;
}
}
static List threadLists = new List ();
static void clearA31Threads ()
{
var threads = threadLists.FindAll ((obj) => { return obj.Name == "A31"; });
foreach (var thread in threads) {
try {
threadLists.Remove (thread);
thread.Abort ();
} catch { }
}
}
static void clearOldThreads ()
{
var threads = threadLists.FindAll ((obj) => { return obj.Name == "Old"; });
foreach (var thread in threads) {
try {
threadLists.Remove (thread);
thread.Abort ();
} catch { }
}
}
public void Show (FrameLayout controlBodyView, FrameLayout bordorView, bool reload)
{
PalyMusicPage = new FrameLayout () {
Width = Application.GetRealWidth (826)
};
controlBodyView.AddChidren (PalyMusicPage);
MusicSourcePage = new FrameLayout () {
X = PalyMusicPage.Right,
Width = Application.GetRealWidth (Application.DesignWidth - 830 - 640),
};
controlBodyView.AddChidren (MusicSourcePage);
var topFrameLayout = new FrameLayout {
Height = Application.GetRealHeight (140),
BackgroundColor = SkinStyle.Current.MainColor,
};
AddChidren (topFrameLayout);
FrameLayout frayout = new FrameLayout {
Width = LayoutParams.MatchParent,
Height = Application.GetRealHeight (Application.DesignHeight - 140 - 140 - 150),
//BackgroundImagePath = "MusicIcon/MusicBackgroun.png",
BackgroundColor = 0xff2F2F2F,
Y = topFrameLayout.Bottom,
};
AddChidren (frayout);
verticalScrolViewLayout = new MusicVerticalScrolViewLayout ();
#region 总音量控制层
var bottomFrameLayout = new FrameLayout {
Height = Application.GetRealHeight (140),
Y = frayout.Bottom,
BackgroundColor = 0xFF181818,
};
AddChidren (bottomFrameLayout);
var voiceVol = new Button {
Width = Application.GetRealWidth (107),
Height = Application.GetRealHeight (127),
X = Application.GetRealWidth (-3),
Gravity = Gravity.CenterVertical,
UnSelectedImagePath = "MusicIcon/PlayVoice.png",
};
bottomFrameLayout.AddChidren (voiceVol);
var frameLayoutVol = new FrameLayout {
Width = Application.GetRealWidth (470),
Height = Application.GetRealHeight (50),
X = Application.GetRealWidth (90),
Gravity = Gravity.CenterVertical,
};
bottomFrameLayout.AddChidren (frameLayoutVol);
allVol = new HorizontalSeekBar {
Width = Application.GetRealWidth (470 - 45),
Height = Application.GetRealHeight (50),
Radius = (uint)Application.GetRealHeight (25),
X = Application.GetRealWidth (13),
Max = 100,
Progress = 50,
SleepTime = 1000,
ProgressColor = 0xffFE5E00,
};
frameLayoutVol.AddChidren (allVol);
allVol.ProgressChanged += allVol_ProgressChanged;
muteVol = new Button {
Width = Application.GetRealWidth (107),
Height = Application.GetRealWidth (127),
X = Application.GetRealWidth (530),
Gravity = Gravity.CenterVertical,
UnSelectedImagePath = "MusicIcon/PlayMute.png",
SelectedImagePath = "MusicIcon/PlayMuteSelected.png",
};
bottomFrameLayout.AddChidren (muteVol);
muteVol.MouseDownEventHandler += MuteVol_MouseDownEventHandler;
#endregion
//主从
verticalScrolViewLayout.ReplaceChanged += (arg1, arg2) => {
if (arg1.Tag.GetType () == typeof (A31MusicModel) && arg2.Tag.GetType () == typeof (A31MusicModel)) {
MainPage.Loading.Start (Language.StringByID (MyInternationalizationString.disposition) + "...");
System.Threading.Tasks.Task.Run (() => {
try {
var serverMusic = arg1.Tag as A31MusicModel;
var clientMusic = arg2.Tag as A31MusicModel;
clearA31Threads ();
var statusEx = openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=getStatusEx");
if (statusEx == null) {
statusEx = openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=getStatusEx");
}
if (statusEx == null) {
return;
}
var a31ssid = Newtonsoft.Json.JsonConvert.DeserializeObject (statusEx);
string ssid = "";
foreach (var b in a31ssid.ssid) {
ssid += System.Convert.ToString (b, 16).ToUpper ().Length < 2 ? "0" + System.Convert.ToString (b, 16).ToUpper () : System.Convert.ToString (b, 16).ToUpper ();
}
var wifiJsonList = openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=wlanGetApList");
if (wifiJsonList == null) {
wifiJsonList = openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=wlanGetApList");
}
if (wifiJsonList == null) {
return;
}
var wifiList = Newtonsoft.Json.JsonConvert.DeserializeObject (wifiJsonList);
var wifiInfo = wifiList.aplist.Find ((obj) => { return obj.ssid == WiimuUPnP.SSID; });
if (wifiInfo == null) {
return;
}
if (null == openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=getNetwork")) {
if (null == openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=getNetwork")) {
return;
}
}
System.Threading.Thread.Sleep (1000);
if (null == openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=ConnectMasterAp:ssid=" + ssid + ":ch=" + wifiInfo.channel + ":auth=" + wifiInfo.auth + ":encry=" + wifiInfo.encry + ":pwd=:chext=" + wifiInfo.extch)) {
if (null == openWeb ("http://" + clientMusic.IPAddress + "/httpapi.asp?command=ConnectMasterAp:ssid=" + ssid + ":ch=" + wifiInfo.channel + ":auth=" + wifiInfo.auth + ":encry=" + wifiInfo.encry + ":pwd=:chext=" + wifiInfo.extch)) {
return;
}
}
System.DateTime dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalSeconds < 10) {
System.Threading.Thread.Sleep (1000);
try {
var result = openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
if (result != null) {
var tmepSlaves = Newtonsoft.Json.JsonConvert.DeserializeObject (result);
if (tmepSlaves.slave_list != null) {
if (null != tmepSlaves.slave_list.Find ((obj) => { return obj.uuid.EndsWith (clientMusic.UniqueDeviceName); })) {
//已经添加成功
break;
}
}
}
} catch { }
}
//关闭server
//openWeb ("http://" + serverMusic.IPAddress + "/httpapi.asp?command=wpscancel");
} catch { } finally {
Application.RunOnMainThread (() => {
MainPage.Loading.Hide ();
MusicSourcePage.RemoveFromParent ();
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
bordorView.RemoveViewByType (typeof (PlayerPage));
PlayerPage mymusic = new PlayerPage ();
bordorView.AddChidren (mymusic);
mymusic.Show (controlBodyView, bordorView, true);
});
}
});
}
};
frayout.AddChidren (verticalScrolViewLayout);
var device = new Button {
TextID = MyInternationalizationString.MusicDevicelist,
Gravity = Gravity.Center,
TextSize = 20,
};
topFrameLayout.AddChidren (device);
var wifi = new Button {
Width = Application.GetMinRealAverage (50),
Height = Application.GetMinRealAverage (50),
UnSelectedImagePath = "MusicIcon/wifi.png",
//UnSelectedImagePath = "MusicIcon/set.png",
X = Application.GetRealWidth (450),
Gravity = Gravity.CenterVertical,
};
topFrameLayout.AddChidren (wifi);
wifi.MouseUpEventHandler += (sender, e) => {
A31Wifimusic a31wifi = new A31Wifimusic ();
bordorView.AddChidren (a31wifi);
a31wifi.show (controlBodyView, bordorView, PalyMusicPage, MusicSourcePage);
};
var a31search = new Button {
Width = Application.GetMinRealAverage (60),
Height = Application.GetMinRealAverage (80),
X = Application.GetRealWidth (535),
Gravity = Gravity.CenterVertical,
UnSelectedImagePath = "MusicIcon/seekdevice.png",
};
topFrameLayout.AddChidren (a31search);
a31search.MouseUpEventHandler += (sender, e) => {
MusicSourcePage.RemoveFromParent ();
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
bordorView.RemoveViewByType (typeof (PlayerPage));
PlayerPage mymusic = new PlayerPage ();
bordorView.AddChidren (mymusic);
mymusic.Show (controlBodyView, bordorView, true);
};
initOldMusic (verticalScrolViewLayout);
if (reload || A31MusicModel.A31MusicModelList.Count == 0) {
refreshDevice (controlBodyView, bordorView, verticalScrolViewLayout);
} else {
clearA31Threads ();
foreach (var a31player in A31MusicModel.A31MusicModelList) {
//这个状态是之前保存的,加载完成后要标记为不在线,后面再读取正确的状态
if (!a31player.IsCanShow) {
continue;
}
//加载界面时默认不在线
a31player.IsOnLine = false;
addViews (controlBodyView, bordorView, a31player);
}
//读取正确的信息,包括IP和端口及名称
seach ((obj) => {
if (obj == null) {
//这里要读取主从关系
readServerOrClientMode (false);
A31MusicModel.Save ();
return;
}
//System.Console.WriteLine (obj.UniqueDeviceName);
var a31MusicModel = A31MusicModel.A31MusicModelList.Find ((music) => { return music.UniqueDeviceName == obj.UniqueDeviceName; });
if (a31MusicModel != null) {
a31MusicModel.IPAddress = obj.IPAddress;
a31MusicModel.Port = obj.Port;
a31MusicModel.Name = obj.Name;
a31MusicModel.IsCanShow = true;
a31MusicModel.IsOnLine = true;
}
});
}
}
//旧音乐
void initOldMusic (MusicVerticalScrolViewLayout verticalScrolViewLayoutt)
{
foreach (Room room in Room.Lists) {
var musiceList = room.DeviceList.FindAll (tempDevice => { return tempDevice.Type == DeviceType.MusicModel; });
foreach (var tempDevice in musiceList) {
var frameLayout = new FrameLayout {
Y = Application.GetRealHeight (20) + verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
X = Application.GetRealWidth (12),
Width = Application.GetRealWidth (640 - 24),
Height = Application.GetRealHeight (190),
BackgroundColor = 0xff181818,
Radius = (uint)Application.GetRealHeight (10),
Tag = tempDevice,
};
verticalScrolViewLayout.AddChidren (frameLayout);
var titelFrameLayout = new FrameLayout () {
Height = Application.GetRealHeight (80),
Y = Application.GetRealHeight (3),
};
frameLayout.AddChidren (titelFrameLayout);
var Living = new Button {
Width = Application.GetRealWidth (300),
Height = Application.GetRealHeight (80),
Text = tempDevice.Name,
TextAlignment = TextAlignment.CenterLeft,
X = Application.GetRealWidth (29),
Gravity = Gravity.CenterVertical,
};
titelFrameLayout.AddChidren (Living);
var btnPlayMusic = new Button {
Width = Application.GetRealWidth (80),
Height = Application.GetRealHeight (80),
X = Application.GetRealWidth (515),//510
Gravity = Gravity.CenterVertical,
UnSelectedImagePath = "MusicIcon/MusicPlay.png",
SelectedImagePath = "MusicIcon/MusicPlaySelected.png",
Tag = tempDevice,
};
titelFrameLayout.AddChidren (btnPlayMusic);
btnPlayMusic.MouseUpEventHandler += (sender, e) => {
Button button = (Button)sender;
if (button.IsSelected) {
button.IsSelected = false;
} else {
button.IsSelected = true;
}
MusicModel musicModel = (MusicModel)button.Tag;
Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*S" + musicModel.SourceID + "PLAYSTOP"));
};
var image = new Button {
Width = Application.GetRealWidth (80),
Height = Application.GetRealHeight (80),
X = Application.GetRealWidth (30),
UnSelectedImagePath = "MusicIcon/musicplay1.png",
Y = Application.GetRealHeight (220 - 130),
Tag = tempDevice,
};
frameLayout.AddChidren (image);
EventHandler playPageEvent = (sender, e) => {
Room.CurrentRoom = room;
Button button = image;
if (((MusicModel)button.Tag).SourceID == "5") {
RadioPage radioPage = new RadioPage ();
MainPage.MainFrameLayout.AddChidren (radioPage);
radioPage.Show ((MusicModel)button.Tag, MusicSourcePage);
} else {
PlayPage playMusic = new PlayPage ();
PalyMusicPage.AddChidren (playMusic);
playMusic.Show ((MusicModel)button.Tag, (button.Tag as MusicModel).SDCardSongList, MusicSourcePage);
}
};
image.MouseUpEventHandler += playPageEvent;
var currentMusicBtn = new TextView {
Width = Application.GetRealWidth (300),
Height = Application.GetRealHeight (50),
X = Application.GetRealWidth (145),
Y = Application.GetRealHeight (210 - 130),
Text = "UnKown",
Tag = tempDevice,
};
frameLayout.AddChidren (currentMusicBtn);
currentMusicBtn.MouseUpEventHandler += playPageEvent;
var voice = new Button {
Width = Application.GetRealWidth (33),
Height = Application.GetRealHeight (31),
X = Application.GetRealWidth (145),
Y = Application.GetRealHeight (275 - 130),
UnSelectedImagePath = "MusicIcon/MusicVoice.png",
};
frameLayout.AddChidren (voice);
var horizontalSeekBarvol = new HorizontalSeekBar {
Width = Application.GetRealWidth (340),
Height = Application.GetRealHeight (50),
Radius = (uint)Application.GetRealHeight (25),
Y = Application.GetRealHeight (275 - 140),
X = Application.GetRealWidth (200),
Max = tempDevice.GetType () == typeof (MusicModel) ? 79 : 100,
Tag = tempDevice,
ProgressColor = 0xffFE5E00,
ThumbRadius = 9,
};
frameLayout.AddChidren (horizontalSeekBarvol);
horizontalSeekBarvol.ProgressChanged += (sender, e) => {
var seekBar = (HorizontalSeekBar)sender;
MusicModel musicModel = (MusicModel)(sender as HorizontalSeekBar).Tag;
Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID,
MusicModel.MusiceBytes ("*Z1VOL" + (79 - seekBar.Progress)));
};
if (tempDevice.Type == DeviceType.MusicModel) {
var music = tempDevice as MusicModel;
System.Threading.Tasks.Task.Run (() => {
System.Threading.Thread.CurrentThread.Name = "Old";
threadLists.Add (System.Threading.Thread.CurrentThread);
var dateTime = DateTime.Now.AddSeconds (-5);
while (true) {
if (5 <= (DateTime.Now - dateTime).TotalSeconds) {
dateTime = DateTime.Now;
Control.ControlBytesSend (Command.ControlMusicModel, music.SubnetID, music.DeviceID, MusicModel.MusiceBytes ("*Z1STATUS?"), SendCount.Zero);
}
Application.RunOnMainThread (() => {
try {
if (music.PlayStatus == MusicModel.Status.Play) {
btnPlayMusic.IsSelected = true;
} else {
btnPlayMusic.IsSelected = false;
}
//当前的音乐名称
currentMusicBtn.Text = music.curPlayMusicName.Replace (".mp3", "") == string.Empty ? "UnKown" : music.curPlayMusicName.Replace (".mp3", "");
horizontalSeekBarvol.Progress = 79 - int.Parse (music.CurVol);
if (verticalScrolViewLayout.ChildrenCount == 1) {
allVol.Progress = 79 - int.Parse (music.CurVol);
}
} catch { }
});
//等待1秒
System.Threading.Thread.Sleep (500);
}
});
}
if (verticalScrolViewLayout.ChildrenCount == 1) {
playPageEvent (currentMusicBtn, new MouseEventArgs ());
}
}
}
}
//搜索A31音乐播放器
void seach (Action action, int time = 2000, string uid = "AllUniqueDeviceName")
{
System.Threading.Tasks.Task.Run (() => {
var socket = new System.Net.Sockets.Socket (System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
for (int i = 10000; i < 65535; i++) {
try {
//绑定本地端口
socket.Bind (new System.Net.IPEndPoint (System.Net.IPAddress.Any, i));//57404
break;
} catch { }
}
System.Threading.Tasks.Task.Run (() => {
var tempDateTime = DateTime.Now;
while ((DateTime.Now - tempDateTime).TotalMilliseconds < time && socket != null) {
try {
StringBuilder stringBuilder = new StringBuilder ();
stringBuilder.AppendLine ("M-SEARCH * HTTP/1.1");
stringBuilder.AppendLine ("St: ssdp:wiimudevice");
stringBuilder.AppendLine ("Mx: 3");
stringBuilder.AppendLine ("Host: 239.255.255.250:1900");
stringBuilder.AppendLine ("Man: \"ssdp:discover\"");
stringBuilder.AppendLine ();
stringBuilder.AppendLine ();
//请求获取A31服务器信息
socket.SendTo (System.Text.Encoding.ASCII.GetBytes (stringBuilder.ToString ()), System.Net.Sockets.SocketFlags.None, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
stringBuilder.Clear ();
stringBuilder.AppendLine ("M-SEARCH * HTTP/1.1");
stringBuilder.AppendLine ("St: urn:schemas-upnp-org:device:MediaServer:1");
stringBuilder.AppendLine ("Mx: 3");
stringBuilder.AppendLine ("Host: 239.255.255.250:1900");
stringBuilder.AppendLine ("Man: \"ssdp:discover\"");
stringBuilder.AppendLine ();
stringBuilder.AppendLine ();
//请求获取A31服务器信息
socket.SendTo (System.Text.Encoding.ASCII.GetBytes (stringBuilder.ToString ()), System.Net.Sockets.SocketFlags.None, new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("239.255.255.250"), 1900));
//如果1000毫秒没有数据回复,就关闭当前Socket,不再等待接收数据
System.Threading.Thread.Sleep (300);
} catch { }
}
try {
if (socket != null) {
socket.Close ();
socket = null;
}
} catch { }
if (action != null) {
System.Console.WriteLine ("查找完成");
//表示完成了
action (null);
}
});
while (socket != null) {
try {
//接收回来的数据
var receviceBytes = new byte [1024];
System.Net.EndPoint remoteIpEndPoint = new System.Net.IPEndPoint (0, 0);
//开始在这里等待接收数据,
var len = socket.ReceiveFrom (receviceBytes, ref remoteIpEndPoint);
var ms = new System.IO.MemoryStream (receviceBytes, 0, len);
var sr = new System.IO.StreamReader (ms);
string tempLine = null;
string ipAddress = null;
int port = 0;
string uniqueDeviceName = null;
//一行一行数据判断,找出需要的信息
while ((tempLine = sr.ReadLine ()) != null) {
//找出Ip地址相关的信息
//System.Console.WriteLine (tempLine);
if (tempLine.StartsWith ("LOCATION: http://")) {
tempLine = tempLine.Replace ("LOCATION: http://", "").Split ('/') [0];
string [] ipAndPort = tempLine.Split (':');
ipAddress = ipAndPort [0];
port = int.Parse (ipAndPort [1]);
} else if (tempLine.StartsWith ("USN: uuid:")) {
uniqueDeviceName = tempLine.Replace ("USN: uuid:", "").Split (':') [0];
}
}
//关闭流
sr.Close ();
ms.Close ();
if (action != null) {
if ("AllUniqueDeviceName" == uid) {
action (new A31MusicModel { IPAddress = ipAddress, Port = port, Name = getDeviceName (ipAddress, port), UniqueDeviceName = uniqueDeviceName });
} else if (uid == uniqueDeviceName) {
if (socket != null) {
socket.Close ();
socket = null;
}
}
}
} catch { }
}
});
}
//加载界面
void addViews (FrameLayout controlBodyView, FrameLayout bordorView, A31MusicModel a31player)
{
var a31frameLayout = new FrameLayout {
Y = Application.GetRealHeight (20) + verticalScrolViewLayout.ChildrenCount * Application.GetRealHeight (190 + 20),
X = Application.GetRealWidth (12),
Width = Application.GetRealWidth (640 - 24),
Height = Application.GetRealHeight (190),
BackgroundColor = 0xff181818,
Radius = (uint)Application.GetRealHeight (10),
Tag = a31player,
};
verticalScrolViewLayout.AddChidren (a31frameLayout);
var a31titelFrameLayout = new FrameLayout {
Height = Application.GetRealHeight (80),
Y = Application.GetRealHeight (3),
};
a31frameLayout.AddChidren (a31titelFrameLayout);
var a31palyername = new Button {
Width = Application.GetRealWidth (350),
Height = Application.GetRealHeight (80),
Text = a31player.Name,
TextAlignment = TextAlignment.CenterLeft,
X = Application.GetRealWidth (29),
Gravity = Gravity.CenterVertical,
Tag=a31player,
};
a31titelFrameLayout.AddChidren (a31palyername);
var colorBtn = new Button {
Height = LayoutParams.MatchParent,
Width = Application.GetRealWidth (5),
BackgroundColor = 0xffFE5E00,
Radius = (uint)Application.GetRealHeight (10),
Visible = false
};
a31frameLayout.AddChidren (colorBtn);
var serverOrClientBtn = new Button {
Width = Application.GetRealWidth (80),
Height = Application.GetRealHeight (80),
X = Application.GetRealWidth (410),
Gravity = Gravity.CenterVertical,
Visible = false
};
serverOrClientBtn.MouseUpEventHandler += (sender, e) => {
clearA31Threads ();
if (a31player.ServerClientType == 1) {
var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.DissolvedGroup),
Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
alert.ResultEventHandler += (sender1, e1) => {
if (e1) {
System.Threading.Tasks.Task.Run (() => {
openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:Ungroup");
seach ((obj) => {
Application.RunOnMainThread (() => {
MusicSourcePage.RemoveFromParent ();
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
bordorView.RemoveViewByType (typeof (PlayerPage));
PlayerPage music = new PlayerPage ();
bordorView.AddChidren (music);
music.Show (controlBodyView, bordorView, true);
});
}, 8000, a31player.UniqueDeviceName);
});
} else { }
};
alert.Show ();
} else if (a31player.ServerClientType == -1) {
var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.Dissolve),
Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
alert.ResultEventHandler += (sender1, e1) => {
if (e1) {
System.Threading.Tasks.Task.Run (() => {
openWeb ("http://" + a31player.ServerIP + "/httpapi.asp?command=multiroom:SlaveKickout:" + a31player.IPAddress);
seach ((obj) => {
Application.RunOnMainThread (() => {
MusicSourcePage.RemoveFromParent ();
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
bordorView.RemoveViewByType (typeof (PlayerPage));
PlayerPage music = new PlayerPage ();
bordorView.AddChidren (music);
music.Show (controlBodyView, bordorView, true);
});
}, 5000, a31player.UniqueDeviceName);
});
} else { }
};
alert.Show ();
}
};
var a31btnPlayMusic = new Button {
Width = Application.GetMinRealAverage (80),
Height = Application.GetMinRealAverage (80),
X = Application.GetRealWidth (518),
Gravity = Gravity.CenterVertical,
UnSelectedImagePath = "MusicIcon/MusicPlay.png",
SelectedImagePath = "MusicIcon/MusicPlaySelected.png",
};
a31titelFrameLayout.AddChidren (a31btnPlayMusic);
a31btnPlayMusic.MouseUpEventHandler += (sender1, e1) => {
if (a31btnPlayMusic.IsSelected) {
a31btnPlayMusic.IsSelected = false;
//sendCommand (a31player, "pause");
a31player.Pause ();
a31player.A31PlayStatus.status = "pause";
} else {
a31btnPlayMusic.IsSelected = true;
//sendCommand (a31player, "resume");
a31player.Play ();
a31player.A31PlayStatus.status = "play";
}
};
var a31image = new ImageView {
Width = Application.GetRealWidth (80),
Height = Application.GetRealHeight (80),
X = Application.GetRealWidth (30),
Y = Application.GetRealHeight (220 - 130),
Radius = (uint)Application.GetRealHeight (8),
ImagePath = "MusicIcon/musicplay1.png",
};
a31frameLayout.AddChidren (a31image);
a31image.MouseLongEventHandler += (sender, e) => {
var alert = new Alert (Language.StringByID (MyInternationalizationString.prompt), Language.StringByID (MyInternationalizationString.Deletemusicplayer),
Language.StringByID (MyInternationalizationString.cancel), Language.StringByID (MyInternationalizationString.confirm));
alert.ResultEventHandler += (sender1, e1) => {
if (e1) {
A31MusicModel.A31MusicModelList.Remove (a31player);
a31frameLayout.RemoveFromParent ();
A31MusicModel.Save ();
MusicSourcePage.RemoveFromParent ();
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
bordorView.RemoveViewByType (typeof (PlayerPage));
PlayerPage mymusic = new PlayerPage ();
bordorView.AddChidren (mymusic);
mymusic.Show (controlBodyView, bordorView, true);
} else { }
};
alert.Show ();
};
var a31currentMusic = new Button {
Width = Application.GetRealWidth (350),
Height = Application.GetRealHeight (50),
X = Application.GetRealWidth (135),
Y = Application.GetRealHeight (190 - 130),
TextSize = 12,
TextAlignment = TextAlignment.CenterLeft,
Text = "UnKown",
};
a31frameLayout.AddChidren (a31currentMusic);
var a31currentartist = new Button {
Height = Application.GetRealHeight (50),
X = Application.GetRealWidth (135),
Y = Application.GetRealHeight (225 - 130),
TextSize = 12,
TextColor = 0x80ffffff,
TextAlignment = TextAlignment.CenterLeft,
Text = "UnKown",
};
a31frameLayout.AddChidren (a31currentartist);
EventHandler sharing = (sender, e) => {
if (-1 == a31player.ServerClientType) {
return;
}
for (int i = 0; i < verticalScrolViewLayout.ChildrenCount; i++) {
var fra = (FrameLayout)verticalScrolViewLayout.GetChildren (i);
if (fra.Tag == a31frameLayout.Tag) {
fra.BackgroundColor = 0xff525252;
} else {
fra.BackgroundColor = 0xff181818;
}
}
A31MusicModel.Current = a31player;
PalyMusicPage.RemoveViewByType (typeof (A31PlayMusicPage));
MusicSourcePage.RemoveViewByType (typeof (A31MusicSourcePage));
A31PlayMusicPage a31playMusic = new A31PlayMusicPage ();
PalyMusicPage.AddChidren (a31playMusic);
a31playMusic.Show (MusicInfo.MusicInfoList, MusicSourcePage, PalyMusicPage, bordorView);
};
a31palyername.MouseUpEventHandler += sharing;
a31image.MouseUpEventHandler += sharing;
a31currentMusic.MouseUpEventHandler += sharing;
a31currentartist.MouseUpEventHandler += sharing;
var a31voice = new Button {
Width = Application.GetRealWidth (33),
Height = Application.GetRealHeight (31),
X = Application.GetRealWidth (135),
Y = Application.GetRealHeight (275 - 130),
UnSelectedImagePath = "MusicIcon/MusicVoice.png",
};
a31frameLayout.AddChidren (a31voice);
var a31horizontalSeekBarvol = new HorizontalSeekBar {
Width = Application.GetRealWidth (380),
Height = Application.GetRealHeight (50),
Radius = (uint)Application.GetRealHeight (25),
Y = Application.GetRealHeight (275 - 140),
X = Application.GetRealWidth (190),
SleepTime = 1000,
ProgressColor = 0xffFE5E00,
ThumbRadius = 9,
Max = 100,
};
a31frameLayout.AddChidren (a31horizontalSeekBarvol);
a31horizontalSeekBarvol.ProgressChanged += (sender1, e1) => {
a31player.ControlVolume (a31horizontalSeekBarvol.Progress);
a31player.A31PlayStatus.vol = a31horizontalSeekBarvol.Progress.ToString ();
};
a31titelFrameLayout.AddChidren (serverOrClientBtn);
if (verticalScrolViewLayout.ChildrenCount == 1) {
sharing (a31currentMusic, new MouseEventArgs ());
}
refreshUI (a31image, a31player, a31horizontalSeekBarvol, a31btnPlayMusic, a31palyername, a31currentMusic, a31currentartist, serverOrClientBtn, a31frameLayout, colorBtn);
System.Threading.Tasks.Task.Run (() => {
System.Threading.Thread.CurrentThread.Name = "A31";
threadLists.Add (System.Threading.Thread.CurrentThread);
string album = null, artist = null;
while (true) {
System.Threading.Thread.Sleep (1000);
if (!a31player.IsOnLine) {
continue;
}
readStatus (a31player, a31image);
Application.RunOnMainThread (() => {
#region 刷新歌手图片
if (a31player.A31PlayStatus.Album != album || a31player.A31PlayStatus.Artist != artist) {
album = a31player.A31PlayStatus.Album;
artist = a31player.A31PlayStatus.Artist;
var path = "";
if (Shared.Application.IsPad) {
path = "Pad/" + "MusicImage/AlbumArtistImage_";
} else {
path = "Phone/" + "MusicImage/AlbumArtistImage_";
}
if (Shared.IO.FileUtils.Exists (path + a31player.A31PlayStatus.Album)) {
a31image.ImagePath = path + a31player.A31PlayStatus.Album;
} else if (Shared.IO.FileUtils.Exists (path + a31player.A31PlayStatus.Artist)) {
a31image.ImagePath = path + a31player.A31PlayStatus.Artist;
} else {
a31image.ImagePath = "MusicIcon/musicplay1.png";
System.Threading.Tasks.Task.Run (() => {
var filePath = Shared.IO.FileUtils.DownLoadImageFormBaidu (album, artist);
if (filePath != null) {
Application.RunOnMainThread (() => {
a31image.ImagePath = filePath;
});
}
});
}
}
#endregion
refreshUI (a31image, a31player, a31horizontalSeekBarvol, a31btnPlayMusic, a31palyername, a31currentMusic, a31currentartist, serverOrClientBtn, a31frameLayout, colorBtn);
});
}
});
}
///
/// 读取主从关系
///
void readServerOrClientMode (bool readType)
{
foreach (var a31player in A31MusicModel.A31MusicModelList) {
if (!a31player.IsOnLine) {
continue;
}
try {
if (readType) {
readMusicType (a31player);
}
a31player.ServerClientType = 0;
var result = openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
if (result == null) {
result = openWeb ("http://" + a31player.IPAddress + "/httpapi.asp?command=multiroom:getSlaveList");
}
if (result != null) {
a31player.Slave = Newtonsoft.Json.JsonConvert.DeserializeObject (result);
}
} catch { }
}
//分析主从关系
foreach (var a31player in A31MusicModel.A31MusicModelList) {
if (!a31player.IsOnLine) {
continue;
}
try {
if ("0" != a31player.Slave.slaves) {
a31player.ServerClientType = 1;//主的
foreach (var slave in a31player.Slave.slave_list) {
var tempA31Player = A31MusicModel.A31MusicModelList.Find ((obj) => { return slave.uuid.EndsWith (obj.UniqueDeviceName); });
if (tempA31Player == null) {
A31MusicModel.A31MusicModelList.Add (new A31MusicModel {
ServerClientType = -1,
IPAddress = slave.ip,
ServerIP = a31player.IPAddress,
Name = slave.name,
});
}
//如果找到就更新为从的
else {
tempA31Player.ServerClientType = -1;//从的
tempA31Player.IPAddress = slave.ip;
tempA31Player.ServerIP = a31player.IPAddress;
tempA31Player.IsCanShow = true;
}
}
}
} catch { }
}
}
///
/// 刷新当前音乐的界面
///
/// A31image.
/// A31player.
/// A31horizontal seek barvol.
/// A31btn play music.
/// A31palyername.
/// A31current music.
/// A31currentartist.
void refreshUI (ImageView a31image, A31MusicModel a31player, HorizontalSeekBar a31horizontalSeekBarvol, Button a31btnPlayMusic, Button a31palyername, Button a31currentMusic, Button a31currentartist, Button serverOrClientBtn, FrameLayout a31frameLayout, Button colorBtn)
{
try {
if (a31player.A31PlayStatus.IsMute) {
a31horizontalSeekBarvol.Progress = 0;
} else {
a31horizontalSeekBarvol.Progress = int.Parse (a31player.A31PlayStatus.vol);
}
a31btnPlayMusic.IsSelected = a31player.A31PlayStatus.status == "play";
a31palyername.Text = a31player.Name;
a31currentMusic.Text = a31player.A31PlayStatus.Title;
a31currentartist.Text = a31player.A31PlayStatus.Artist;
{
a31btnPlayMusic.Alpha = 1.0f;
a31btnPlayMusic.Enable = true;
a31image.Alpha = 1.0f;
a31palyername.Enable = true;
a31currentMusic.Alpha = 1.0f;
a31currentMusic.Enable = true;
}
if (1 == a31player.ServerClientType) {
colorBtn.Visible = false;
serverOrClientBtn.Visible = true;
serverOrClientBtn.UnSelectedImagePath = "MusicIcon/lifeSelected.png";
} else if (-1 == a31player.ServerClientType) {
colorBtn.Visible = true;
serverOrClientBtn.Visible = true;
serverOrClientBtn.UnSelectedImagePath = "MusicIcon/life.png";
a31btnPlayMusic.Alpha = 0.5f;
a31btnPlayMusic.Enable = false;
a31image.Alpha = 0.5f;
a31palyername.Enable = false;
a31currentMusic.Alpha = 0.5f;
a31currentMusic.Enable = false;
}
} catch { }
}
//刷新播放器设备列表
void refreshDevice (FrameLayout controlBodyView, FrameLayout bordorView, MusicVerticalScrolViewLayout verticalScrolViewLayout)
{
clearA31Threads ();
foreach (var a31player in A31MusicModel.A31MusicModelList) {
a31player.IsCanShow = false;
a31player.IsOnLine = false;
}
MainPage.Loading.Start ();
seach ((obj) => {
if (obj == null) {
readServerOrClientMode (true);
A31MusicModel.Save ();
Application.RunOnMainThread (() => {
MainPage.Loading.Hide ();
foreach (var a31player in A31MusicModel.A31MusicModelList) {
//这个状态是之前保存的,加载完成后要标记为不在线,后面再读取正确的状态
if (!a31player.IsCanShow) {
continue;
}
addViews (controlBodyView, bordorView, a31player);
}
});
return;
}
//System.Console.WriteLine (obj.UniqueDeviceName);
var a31MusicModel = A31MusicModel.A31MusicModelList.Find ((music) => { return music.UniqueDeviceName == obj.UniqueDeviceName; });
if (a31MusicModel == null) {
//不是我们支持的品牌不支持
if (obj.Name != null) {
A31MusicModel.A31MusicModelList.Add (obj);
}
} else {
a31MusicModel.IPAddress = obj.IPAddress;
a31MusicModel.Port = obj.Port;
a31MusicModel.Name = obj.Name;
a31MusicModel.IsCanShow = true;
a31MusicModel.IsOnLine = true;
}
});
}
//标记播放器类型是否有蓝牙功能。
void readMusicType (A31MusicModel a31player)
{
int tempDeviceType = 0;
Action action = (subnetID, deviceId, deviceType, command, targetSubnetID, targetDeviceID, usefullBytes, ipEndPoint) => {
if (command == Command.ReadRemarkACK && ipEndPoint.Address.ToString () == a31player.IPAddress.ToString ()) {
tempDeviceType = deviceType;
}
};
Packet.ReceviceAllDadaAction += action;
DateTime dateTime = DateTime.Now;
while ((DateTime.Now - dateTime).TotalMilliseconds <= 1000) {
Control.ControlBytesSend (Command.ReadRemark, 255, 255, new byte [] { (byte)new Random ().Next (0, 255), (byte)new Random ().Next (0, 255) }, SendCount.One, new System.Net.IPEndPoint (System.Net.IPAddress.Parse (a31player.IPAddress), 6000));
System.Threading.Thread.Sleep (200);
if (tempDeviceType != 0) {
a31player.A31DeviceType = tempDeviceType;
break;
}
}
Packet.ReceviceAllDadaAction -= action;
}
///
/// 更新A31播放器的状态
///
///
void readStatus (A31MusicModel a31MusicModel, ImageView imageView)
{
System.IO.StringReader sr = null;
try {
if (a31MusicModel.ServerClientType == -1) {
var result = openWeb ("http://" + a31MusicModel.ServerIP + "/httpapi.asp?command=multiroom:getSlaveList");
if (result != null) {
var slaves = Newtonsoft.Json.JsonConvert.DeserializeObject (result);
var slave = slaves.slave_list.Find ((obj) => { return obj.uuid.EndsWith (a31MusicModel.UniqueDeviceName); });
a31MusicModel.A31PlayStatus.vol = slave.volume;
}
return;
}
Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient (1000);
webClient.Headers.Add ("Soapaction", "\"urn:schemas-upnp-org:service:AVTransport:1#GetInfoEx\"");
webClient.Headers.Add ("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
var recevieBytes = webClient.UploadData (new Uri ("http://" + a31MusicModel.IPAddress + ":" + a31MusicModel.Port + "/upnp/control/rendertransport1"), "POST", System.Text.Encoding.UTF8.GetBytes ("0"));
a31MusicModel.LastDateTime = DateTime.Now;
var se = System.Security.SecurityElement.FromString (System.Text.Encoding.UTF8.GetString (recevieBytes)).SearchForChildByTag ("s:Body").SearchForChildByTag ("u:GetInfoExResponse");
// System.Console.WriteLine (se);
if ("PLAYING" == se.SearchForTextOfTag ("CurrentTransportState")) {
a31MusicModel.A31PlayStatus.status = "play";
} else {
a31MusicModel.A31PlayStatus.status = "stop";
}
a31MusicModel.A31PlayStatus.totlen = (DateTime.Parse (se.SearchForTextOfTag ("TrackDuration")) - DateTime.Parse ("00:00:00")).TotalMilliseconds.ToString ();
var artist = a31MusicModel.A31PlayStatus.Artist;
var album = a31MusicModel.A31PlayStatus.Album;
var trackMetaData = se.SearchForTextOfTag ("TrackMetaData");
if (string.IsNullOrEmpty (trackMetaData)) {
return;
}
if (A31MusicModel.IsJson (trackMetaData)) {
var a31QQSong = Newtonsoft.Json.JsonConvert.DeserializeObject (trackMetaData);
a31MusicModel.A31PlayStatus.Title = a31QQSong.title;
a31MusicModel.A31PlayStatus.Album = a31QQSong.album;
a31MusicModel.A31PlayStatus.Artist = a31QQSong.creator;
} else {
var metadata = trackMetaData.Replace ("", "").Replace ("&", "&");
var item = SecurityElement.FromString (metadata).SearchForChildByTag ("item");
a31MusicModel.A31PlayStatus.Title = item.SearchForTextOfTag ("dc:title");
a31MusicModel.A31PlayStatus.Artist = item.SearchForTextOfTag ("upnp:artist");
a31MusicModel.A31PlayStatus.Album = item.SearchForTextOfTag ("upnp:album");
}
a31MusicModel.A31PlayStatus.curpos = (DateTime.Parse (se.SearchForTextOfTag ("RelTime")) - DateTime.Parse ("00:00:00")).TotalMilliseconds.ToString ();
a31MusicModel.A31PlayStatus.vol = se.SearchForTextOfTag ("CurrentVolume");
a31MusicModel.A31PlayStatus.loop = se.SearchForTextOfTag ("LoopMode");
a31MusicModel.A31PlayStatus.Source = se.SearchForTextOfTag ("PlayMedium");
a31MusicModel.A31PlayStatus.playSource = se.SearchForTextOfTag ("TrackSource");
a31MusicModel.A31PlayStatus.TrackURL = se.SearchForTextOfTag ("TrackURI");
} catch { } finally {
if (sr != null) {
sr.Close ();
}
}
}
///
/// 获取A31的名称
///
///
///
///
string getDeviceName (string ip, int port)
{
string deviceName = null;
System.IO.StreamReader sr = null;
Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient ();
try {
var receviceBytes = webClient.DownloadData (new Uri ("http://" + ip + ":" + port + "/description.xml"));
sr = new System.IO.StreamReader (new System.IO.MemoryStream (receviceBytes), Encoding.UTF8);
string line = null;
string deviceType = null;
while ((line = sr.ReadLine ()) != null) {
//System.Console.WriteLine (line);
if (line.StartsWith ("")) {
deviceName = line.Replace ("", "").Replace ("", "");
} else if (line.StartsWith ("")) {
deviceType = line.Replace ("", "").Replace ("", "");
}
}
switch (deviceType) {
case "iEAST":
case "Linkplay Technology Inc.":
break;
//不是A31的音乐数据
default:
deviceName = null;
break;
}
} catch { } finally {
if (sr != null) {
sr.Close ();
}
}
return deviceName;
}
///
/// 1秒更新一次
///
public static System.DateTime dateTime = System.DateTime.Now.AddSeconds (-1);
void sendCommand (A31MusicModel a31, string cmd)
{
System.Threading.Tasks.Task.Run (() => {
Shared.Net.MyWebClient webClient = new Shared.Net.MyWebClient ();
try {
byte [] recevieBytes1 = webClient.DownloadData (new Uri ("http://" + a31.IPAddress + "/httpapi.asp?command=setPlayerCmd:" + cmd));
} catch { }
});
}
private void allVol_ProgressChanged (object sender, int e)
{
for (int index = 0; index < verticalScrolViewLayout.ChildrenCount; index++) {
object tag = verticalScrolViewLayout.GetChildren (index).Tag;
if (tag == null) {
continue;
}
if (tag.GetType () == typeof (A31MusicModel)) {
var a31MusicModel = tag as A31MusicModel;
a31MusicModel.A31PlayStatus.vol = e.ToString ();
a31MusicModel.ControlVolume (int.Parse (a31MusicModel.A31PlayStatus.vol));
} else if (tag.GetType () == typeof (MusicModel)) {
var musicModel = tag as MusicModel;
musicModel.CurVol = (79 - e).ToString ();
Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*Z1VOL" + musicModel.CurVol));
}
}
}
string beforeVol = "30";
private void MuteVol_MouseDownEventHandler (object sender, MouseEventArgs e)
{
muteVol.IsSelected = !muteVol.IsSelected;
if (muteVol.IsSelected) {
//静音之前先保存之前的音量
beforeVol = allVol.Progress.ToString ();
allVol.Progress = 0;
//muteVol.IsSelected = true;
} else {
allVol.Progress = int.Parse (beforeVol);
//muteVol.IsSelected = false;
}
for (int index = 0; index < verticalScrolViewLayout.ChildrenCount; index++) {
object tag = verticalScrolViewLayout.GetChildren (index).Tag;
if (tag == null) {
continue;
}
if (tag.GetType () == typeof (A31MusicModel)) {
var a31MusicModel = tag as A31MusicModel;
a31MusicModel.A31PlayStatus.vol = allVol.Progress.ToString ();
a31MusicModel.ControlVolume (int.Parse (a31MusicModel.A31PlayStatus.vol));
} else if (tag.GetType () == typeof (MusicModel)) {
var musicModel = tag as MusicModel;
musicModel.CurVol = (79 - allVol.Progress).ToString ();
Control.ControlBytesSend (Command.ControlMusicModel, musicModel.SubnetID, musicModel.DeviceID, MusicModel.MusiceBytes ("*Z1VOL" + musicModel.CurVol));
}
}
}
private void back_MouseDownEventHandler (object sender, MouseEventArgs e)
{
RemoveFromParent ();
}
class a31wifimessage
{
static a31wifimessage ()
{
new a31wifimessage ();
}
public a31wifimessage ()
{
res = null;
aplist = null;
}
public string res;
public List aplist;
}
class a31message
{
static a31message ()
{
new a31message ();
}
public a31message ()
{
ssid = null;
channel = null;
auth = null;
encry = null;
extch = null;
}
public string ssid;
public string channel;
public string auth;
public string encry;
public string extch;
}
class a31wifi
{
static a31wifi ()
{
new a31wifi ();
}
public a31wifi ()
{
ssid = null;
}
public string ssid;
}
}
}