using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using parkMonitor.entity;
using System.Configuration;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using parkMonitor.tools;
using parkMonitor.LOG;
using MySql.Data.MySqlClient;
namespace centralController.WebServer
{
///
/// web线程类,接收用户指令
///
public class CentralForWeb : IWebServer
{
public MultiSocketThread multiSocketThread { set; get; }
public static BlockingQueue blockingQueue = new BlockingQueue();
private Queue reserveQueue = null;
private object reserveLock = new object();
Int32 port;
IPAddress localAddr;
bool isClosing;
//public AbstractMessage GetMessage()
//{
// return (AbstractMessage)blockingQueue.Dequeue();
//}
private void WebConnect(TcpListener listener)
{
try
{
if (listener != null)
{
//得到包含客户端信息的套接字
var tcpClient = listener.AcceptTcpClient();
//创建消息服务线程对象
//把multiSocket类的run方法委托给线程
multiSocketThread = new MultiSocketThread(tcpClient);
Thread newThread = new Thread(multiSocketThread.Run);
newThread.IsBackground = true;
newThread.Start();
}
}
catch (Exception e)
{
if (multiSocketThread != null)
multiSocketThread.Close();
Console.WriteLine(e.Message);
throw new Exception();
}
}
private void Run()
{
bool linked = false;
//web重连机制
Task.Factory.StartNew(() =>
{
TcpListener listener = null;
try
{
listener = LazySingleton.GetInstance(localAddr, port);
listener.Start();
linked = true;
}
catch (Exception) { Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常"); linked = false; }
while (isClosing)
{
try
{
while (linked)
{
WebConnect(listener);
}
if (!linked)
{
throw new Exception();
}
}
catch (Exception)
{
//Task.Factory.StartNew(() =>
//{
MyTimer mt = new MyTimer();
mt.StartTiming();
while (!linked)
{
Thread.Sleep(10000);
try
{
listener = LazySingleton.GetInstance(localAddr, port);
listener.Start();
linked = true;
Console.WriteLine("web已成功重连");
break;
}
catch (Exception)
{
mt.EndTiming();
int count = 0;
if (mt.IsLonger(30, 1, true, out count))
{
Console.WriteLine("未能与Web服务器连接,本地ip错误或网络异常");
}
}
}
//});
}
Thread.Sleep(5000);
}
if (multiSocketThread != null)
multiSocketThread.Close();
});
//处理接收到的指令
Task.Factory.StartNew(() =>
{
while (!isClosing)
{
object obj = blockingQueue.Dequeue();
if (obj.GetType().Equals(typeof(MessageUTF8)))
{
MessageUTF8 msg = (MessageUTF8)obj;
switch (msg.cmd)
{
//预约停
case "a":
lock (reserveLock)
{
reserveQueue.Enqueue(msg);
}
//通知PLC减少可预约车位数
//预约记录写入db并更新车辆状态
string vehicleStateChangeSql = "update vehicle set vehiclepParkState =" + 4 + " where numberPlate = '" + msg.context + "';";
Monitor.Monitor.localDBOper.Query(vehicleStateChangeSql);
break;
//预约取
case "b":
break;
//更新广告
case "c":
string adAlert = "";
bool result = Monitor.Monitor.advertMgr.UpdateAdvert(out adAlert);
if (!result)
{
Monitor.Monitor.SetNotification("广告更新失败,请尝试手动更新",parkMonitor.model.TextColor.Error);
}
else
{
Monitor.Monitor.SetNotification("广告更新成功\n" + adAlert,parkMonitor.model.TextColor.Info);
}
break;
default:
Monitor.Monitor.SetNotification("接收到无法识别的指令",parkMonitor.model.TextColor.Warning);
break;
}
}
}
});
//处理超时预约指令
Task.Factory.StartNew(() =>
{
while (!isClosing)
{
lock (reserveLock)
{
for (int i = 0; i < reserveQueue.Count; i++)
{
try
{
MessageUTF8 msg = reserveQueue.Dequeue();
DateTime startTime = DateTime.Parse(msg.bookTime);
if ((DateTime.Now - startTime).TotalMinutes > msg.bookLength * 60)
{
//通知PLC将可预约车位数恢复一个
}
else
{
reserveQueue.Enqueue(msg);
}
}
catch { }
}
}
Thread.Sleep(5000);
}
});
}
private void InsertOrderRecords(string license)
{
string insertSql = "";
List strs = new List();
strs.Add(insertSql);
Monitor.Monitor.localDBOper.Insert(strs);
}
private void DownloadAds()
{
}
///
/// 启动
///
public bool Start(int port)
{
//string strTemp = ConfigurationManager.AppSettings["WebConfig"];
//string[] strArray = strTemp.Split(':');
//string ipstr = strArray[0];
//string portstr = strArray[1];
//获取本机ip地址
try
{
TcpClient client = new TcpClient();
client.Connect("www.baidu.com", 80);
string ip = ((IPEndPoint)client.Client.LocalEndPoint).Address.ToString();
client.Close();
localAddr = IPAddress.Parse(ip);
this.port = port;//Convert.ToInt32(ConfigurationManager.AppSettings["webPort"]);
reserveQueue = new Queue();
Console.WriteLine(ip.ToString());
}
catch (Exception e) { Console.WriteLine("wrong ipAddr"); return false; }
Run();
return true;
}
///
/// 停止
///
public void Stop()
{
isClosing = true;
}
///
/// 预约停车记录
///
public void BookParkRecord()
{
}
///
/// 预约取车记录
///
public void BookFetchRecord()
{
}
public bool ReservedCarCheck(string license)
{
throw new NotImplementedException();
}
}
}