Commit eda8bcfe 刘韬

添加项目文件。

1 个父辈 4c2aa079
正在显示 165 个修改的文件 包含 5052 行增加0 行删除

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30907.101
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoadCSVLibrary", "LoadCVSLibrary\LoadCSVLibrary.csproj", "{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{43CDD09E-FCF3-4960-A01D-3BBFE9933122}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeviceLibrary", "DeviceLibrary\DeviceLibrary.csproj", "{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheMachine", "TheMachine\TheMachine.csproj", "{61FDFF14-8BB7-439A-85A0-592E3011F4C4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Debug|Any CPU.Build.0 = Debug|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Release|Any CPU.ActiveCfg = Release|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Release|Any CPU.Build.0 = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.Build.0 = Release|Any CPU
{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}.Release|Any CPU.Build.0 = Release|Any CPU
{61FDFF14-8BB7-439A-85A0-592E3011F4C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{61FDFF14-8BB7-439A-85A0-592E3011F4C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{61FDFF14-8BB7-439A-85A0-592E3011F4C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{61FDFF14-8BB7-439A-85A0-592E3011F4C4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BA4F2116-5AFF-4DE1-9860-4A389EDBD60D}
EndGlobalSection
EndGlobal
此文件的差异被折叠, 点击展开。
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{43CDD09E-FCF3-4960-A01D-3BBFE9933122}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OnlineStore.Common</RootNamespace>
<AssemblyName>MyCommon</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="ConfigHelper">
<HintPath>..\..\ConfigHelper\ConfigHelper\bin\Debug\ConfigHelper.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\增广夹爪\Rmaxis\bin\Debug\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="bean\Bean.cs" />
<Compile Include="CodeResourceControl.cs" />
<Compile Include="ColorHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Setting_Init.cs" />
<Compile Include="StringList.cs" />
<Compile Include="util\AcSerialBean.cs" />
<Compile Include="util\ConfigAppSettings.cs" />
<Compile Include="util\FormUtil.cs" />
<Compile Include="util\HumitureController.cs" />
<Compile Include="util\HumitureServer.cs" />
<Compile Include="util\JsonHelper.cs" />
<Compile Include="util\LogUtil.cs" />
<Compile Include="util\MyWebClient.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="util\NetTCPServer.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="util\CTcpClient.cs" />
<Compile Include="util\SMF.cs" />
<Compile Include="util\TcpServer.cs" />
<Compile Include="util\UdpServer.cs" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file \ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("f8eab140-5f98-4df7-842c-0d866e759c9a")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConfigHelper;
namespace OnlineStore.Common
{
/// <summary>
/// 记录配置的key
/// </summary>
public class Setting_Init
{
[MyConfigComment("程序开机自启动")]
public static MyConfig<bool> App_AutoRun = false;
/// <summary>
/// 系统主界面标题
/// </summary>
[MyConfigComment("系统主界面标题")]
public static MyConfig<string> App_Title="出库机构";
[MyConfigComment("服务器地址")]
public static MyConfig<string> Device_Server_Address = "http://192.168.1.243/smf-core";
[MyConfigComment("设备界面语言")]
public static MyConfig<string> Device_Default_Language = "zh-CN";
[MyConfigComment("设备ID")]
public static MyConfig<string> Device_CID = "01";
[MyConfigComment("是否启用蜂鸣器")]
public static MyConfig<bool> Device_EnableBuzzer = true;
[MyConfigComment("屏蔽升降轴调试保护")]
public static MyConfig<bool> Device_DisableUpdownProtect = false;
[MyConfigComment("屏蔽出入库时料叉检测")]
public static MyConfig<bool> Device_Disable_INOUT_FixtureCheck = false;
[MyConfigComment("管理员密码")]
public static MyConfig<string> User_AdminPassword = "123456";
[MyConfigComment("启用管理员密码")]
public static MyConfig<bool> User_Enable = false;
/// <summary>
/// 摄像机名称
/// </summary>
[MyConfigComment("摄像机名称IN_1")]
public static MyConfig<string[]> CameraScan_IN_1 = new string[] { };
[MyConfigComment("摄像机名称IN_2")]
public static MyConfig<string[]> CameraScan_IN_2 = new string[] { };
[MyConfigComment("扫码类型清单#号分割")]
public static MyConfig<string> CameraScan_CodeType = "QR Code#Data Matrix ECC 200";
[MyConfigComment("扫码学习文件保存目录")]
public static MyConfig<string> CameraScan_CodeParamPath = "CodeParam";
[MyConfigComment("二维码扫码最大数量")]
public static MyConfig<int> CameraScan_QRCodeCount = 3;
[MyConfigComment("二维码扫码超时毫秒")]
public static MyConfig<int> CameraScan_CodeTimeOut = 3000;
public static MyConfig<bool> Runtime_IsInStore;
public static MyConfig<string> Runtime_PosID;
public static MyConfig<string> Runtime_WareCode;
public static MyConfig<int> Runtime_PlateW;
public static MyConfig<int> Runtime_PlateH;
public static MyConfig<string> Runtime_PlateInFix;
public static MyConfig<bool> Runtime_IsNg;
public static MyConfig<string> Runtime_NgMsg;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.Common
{
public enum L
{
enable_config_mode,
disable_config_mode,
safty_release_string,
safty_releaseing_string,
safty_releaseed_string,
connect_fail,
humidity,
temperature,
current_status,
device_initializing,
tab_io,
tab_axis,
tab_store,
tab_setting,
tab_log,
table_datetime,
table_info,
table_module,
table_step,
device_isrunning_cant_exit,
start,
device_pause,
device_resume,
device_suddenstop_cant_start,
open_debug_mode,
iocard_init_fail,
tempnhum_sensor_init_fail,
cant_find_storeposfile,
transfer_equipment,
string_inout_equipment,
clamp_equipment,
store_manage_equipment,
reset_equipment,
autotest_inout_equipment,
Clamp_Axis_interference_01,
Clamp_Axis_interference_02,
Clamp_Axis_interference_03,
Middle_Axis_interference_01,
UpDown_Axis_interference_01,
out_store_wait_ngdoor_ready,
out_store_not_detect_material,
out_store_detect_material,
out_store_wait_string_ready,
in_store_detect_material,
wait_reel_transfer,
reset_press,
reset_press_with_sudden,
runbtn_press,
system_is_running,
runbtn_press_with_sudden,
not_detect_airpressure,
x29_low_no_reel,
wait_put_reel_into_ngdoor,
ignored,
SafetyLight_is_block,
left_safedoor_not_close,
right_safedoor_not_close,
back_safedoor_not_close,
x29_higt_has_reel,
system_pause,
in_suddenstop,
system_need_reset,
store_inout_debug_mode,
airpressure_not_enough,
motion_alarm,
wait_detect_reel_height,
wait_user_select_pos,
wait_server_response_pos,
reel_wait_in_store,
please_take_ngdoor_reel,
no_string,
wait_stringdoor_close,
detect_string,
string_ready_for_get,
out_store_free,
string_ready_for_put,
in_store_ng,
posnum,
not_detect_reel_height,
not_detect_reel_code,
scan_code_timeout,
wait_server_response_pos_timeout,
string_releasing,
ngdoor,
scanning_code,
taking_code,
no_info_reel,
ngdoor_reel_out,
timeout,
wait,
empty_reel,
full_reel,
instore_reel,
string_prepare,
free,
reel_outting,
reel_ining,
FrmPositionTool_serv_state,
FrmPositionTool_enable,
FrmPositionTool_disable,
FrmPositionTool_homests,
FrmPositionTool_finish,
FrmPositionTool_unfinish,
FrmPositionTool_busysts,
FrmPositionTool_busying,
detect_signal,
reel_not_onposition_cant_manual_in,
stop_inout_test,
start_device_first,
tips,
autotest_msg_01,
autotest_msg_02,
stop_auto_test,
start_auto_test,
store_busy_cant_manual_out,
monitor_open_fail,
monitor_config_load_fail,
monitor_config_not_exist,
AxisMoveControl_status_monitor,
string_full_takeout,
string_not_onposition,
in_store_nothave_position,
begin_singlein,
Clamp_Axis_running_cant_singlein,
string_begin_release,
store_running_cant_inout,
close_singledoor,
not_in_single_prosses,
begin_open_string_door,
batch_door_not_close_cant_lock,
begin_lock_batch_door,
tray_detect_reel_01,
system_running_cantmove,
before_FrmPositionTool_stopmuchine,
wait_ngdoor_close,
out_string,
InOut_Axis_interference_01,
string_manual_takeout
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.Common
{
public class LineGetPosOp
{
public LineGetPosOp(string cids,string code)
{
this.cids = cids;
this.code = code;
}
public string cids = "";
public string code = "";
}
public class LineOperation
{
// //{"result":"0","msg":"","pos":"11#AC1_18_4_28","barcode":"R506072019102200414","cid":"line-ac-11"}
// 返回: {"code": 0, "msg":"ok", data:7}
/// <summary>
/// 0=成功
/// </summary>
public int result;
public string cid;
public string msg = "";
public string pos = "";
public string barcode = "";
}
/// <summary>
/// 与服务器通信用对象
/// </summary>
public class Operation
{
/// <summary>
/// 料仓唯一标识,分号分割
/// </summary>
private string _cid = "";
public string cid
{
get { return _cid; }
set { _cid = value; }
}
/// <summary>
/// 请求序列号
/// </summary>
public int seq { get; set; }
/// <summary>
/// 操作码(0无操作(发送料仓状态给服务器),
/// 1扫码入库(扫码成功后发送给服务器),
/// 2 出库(服务器发送),3表示错误信息 )
/// 4,发送给服务表示二维码扫码入库,收到开始扫码
/// </summary>
public int op { get; set; }
/// <summary>
/// 操作相关数据,
/// op=1时,客户端发送 code 二维码给服务器,服务器返回时有:posId库位编号,plateW:料盘宽度,plateH:料盘高度
/// 如果需要更新温湿度的报警值,服务器会发送alarmTemperature,alarmHumidity给客户端,客户端缓存,如果没有发送,不处理
/// op=3时,data发送BoxID和AlarmCode
/// =4时扫码入库
/// =5时服务器发送预警温度
/// </summary>
private Dictionary<string, string> _data = new Dictionary<string, string>();
public Dictionary<string, string> data
{
get { return _data; }
set { _data = value; }
}
/// <summary>
/// 整体料仓状态
/// 1=正常运行中
/// 2=急停中
/// 3=故障(气压检测不到等,用msg发送详细故障说明)
/// 4=警告(用msg发送提醒,如出库到达工位但是没有工人操作)
/// </summary>
public int status { get; set; }
/// <summary>
/// 提示消息
/// 出入库错误: BOX正在调试中,不能出入库
/// 出入库错误: 急停了不能出入库
/// 入库错误:料盘过大,放不到指定的位置中去
/// 故障:气压信号检测不到
/// 警告:出库盘到达工位但是没有工人操作
/// </summary>
public string msg { get; set; }
// public Dictionary<string, string> msgData { get; set; } = new Dictionary<string, string>() { {"zh","" },{ "en", "" }, { "jp", "" } };
public Dictionary<string, string> msgData { get; set; } = new Dictionary<string, string>();
public string msgParam { get; set; }
public string msgCode { get; set; }
public string msgEn { get; set; }
public string msgJp { get; set; }
/// <summary>
/// 包含的多个 BOX 的状态信息
/// </summary>
public Dictionary<int, BoxStatus> boxStatus = new Dictionary<int, BoxStatus>();
/// <summary>
/// 报警集合
/// </summary>
public List<AlarmInfo> alarmList = new List<AlarmInfo>();
}
/// <summary>
/// 单台料仓状态(包含流水线)
/// </summary>
public class BoxStatus
{
/// <summary>
/// Box编号,从1开始
/// </summary>
public int boxId { get; set; }
/// <summary>
/// 单台BOX状态
/// 急停,故障,调试中,就绪状态(正常待机)
/// 入库执行中,入库完成,入库失败
/// 出库执行中,出库完成,出库失败
/// </summary>
public int status { get; set; }
/// <summary>
/// 单台BOX的消息
/// 正在调试中,不能出入库
/// 入库失败原因:
/// 出库失败原因:
/// </summary>
public string msg { get; set; }
/// <summary>
/// 温度
/// </summary>
public string temperature { get; set; }
/// <summary>
/// 湿度
/// </summary>
public string humidity { get; set; }
/// <summary>
/// 操作相关数据,
/// 出库完成后发送posId库位编号给服务器
/// </summary>
private Dictionary<string, string> _data = new Dictionary<string, string>();
public Dictionary<string, string> data
{
get { return _data; }
set { _data = value; }
}
}
public class AlarmInfo
{
public AlarmInfo(int StoreID, int aType, string alarmDetial, string WarnMsg, int inoutStatus)
{
// TODO: Complete member initialization
this.boxId = StoreID;
this.alarmType = aType;
this.alarmDetail = alarmDetial;
this.alarmMsg = WarnMsg;
this.inOutStatus = inoutStatus;
}
public AlarmInfo()
{
// TODO: Complete member initialization
}
/// <summary>
/// 料仓ID,0表示流水线
/// </summary>
public int boxId { get; set; }
/// <summary>
/// 报警类型,
/// </summary>
public int alarmType { get; set; }
/// <summary>
/// 报警详情
///AlarmType= 0 消息 "1=原点返回
//AlarmType= 0 消息 2=复位"
//AlarmType=1 总体错误 "1=急停
//AlarmType=1 总体错误 2=没有气压信号
//AlarmType=1 总体错误,3=盘错乱"
//AlarmType=2 运动轴错误 1=第一轴(旋转)
//AlarmType=2 运动轴错误 2=第二轴(上下轴)
//AlarmType=2 运动轴错误 3=第三轴(前进轴)
//AlarmType=2 运动轴错误 4=第四轴(压紧轴)"
//AlarmType=2 电钢报警 5=上下电钢
//AlarmType=3 IO报警,信号超时 io电器定义(电器定义)
/// </summary>
public string alarmDetail { get; set; }
/// <summary>
/// 报警消息
/// </summary>
public string alarmMsg { get; set; }
/// <summary>
/// 0,1=入库,2=出库
/// </summary>
public int inOutStatus { get; set; }
}
public class ParamDefine
{
/// <summary>
/// 库位 ID
/// </summary>
public static string posId = "posId";
/// <summary>
/// 料盘宽
/// </summary>
public static string plateW = "plateW";
/// <summary>
/// 料盘高
/// </summary>
public static string plateH = "plateH";
public static string singleOut = "singleOut";
/// <summary>
/// 料仓ID
/// </summary>
public static string storeId = "storeId";
/// <summary>
/// 报警码
/// </summary>
public static string alarmCode = "alarmCode";
/// <summary>
/// 报警详情或参数
/// </summary>
public static string alarmDetial = "alarmDetial";
/// <summary>
/// 湿度报警值
/// </summary>
public static string maxHumidity = "humi";
/// <summary>
/// 温度报警值
/// </summary>
public static string maxTemperature = "temp";
/// <summary>
/// urgentReel: true 表示紧急料,需要出到料串上
/// </summary>
public static string urgentReel = "urgentReel";
/// <summary>
/// cutReel: true 表示分盘料,需要出到料串上
/// </summary>
public static string cutReel = "cutReel";
/// <summary>
/// smallReel: true 小料(7x8),放置到小料串上
/// </summary>
public static string smallReel = "smallReel";
/// <summary>
/// rfid: 分配的料串RFID
/// </summary>
public static string rfid = "rfid";
/// <summary>
/// rfidLoc: 料串的架位,值为 - 1时,可以自由分配皮带线, 小料时,架位为1 - 46优先走1 / 2号皮带线,47 - 92优先走3 / 4号皮带线,
/// 70,71,72时只能分配到3 / 4号皮带线; 大料时,架位1 - 6优先走1 / 2号皮带线, 7 - 12优先走3 / 4号皮带线
/// </summary>
public static string rfidLoc = "rfidLoc";
public static string barcode = "barcode";
/// <summary>
/// 打开门锁动作
/// </summary>
public static string openLock = "openLock";
/// <summary>
/// 批量出入库动作
/// </summary>
public static string startBatchIn = "startBatchIn";
/// <summary>
/// 关闭门锁
/// </summary>
public static string closeLock = "closeLock";
/// <summary>
/// 取出出库料盘动作
/// </summary>
public static string takeOutReel = "takeOutReel";
/// <summary>
/// 门口料盘已取出
/// </summary>
public static string confirmReelOut = "confirmReelOut";
/// <summary>
/// 单盘入库按钮
/// </summary>
public static string singleReelIn = "singleReelIn";
public static string doorStatus = "doorStatus";
public static string doit = "doit";
public static string enable = "enable";
public static string disable = "disable";
public static string queueTaskCount="queueTaskCount";
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net461" />
</packages>
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
namespace OnlineStore.Common
{
public class CTcpClient
{
// public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void HandleMessage(string message);
private Socket m_clientSocket = null;
private byte[] m_receiveBuffer = new byte[1024];
private HandleMessage onReceived;
public int TimeOutTime = 0;
/// <summary>
/// 当前连接状态
/// </summary>
public bool IsConnected()
{
if (m_clientSocket == null)
{
return false;
}
if (m_clientSocket.Connected)
{
return true;
}
#region remarks
/********************************************************************************************
* 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。
* 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;
* 否则,该套接字不再处于连接状态。
* Depending on http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
********************************************************************************************/
#endregion
try
{
#region 过程
// This is how you can determine whether a socket is still connected.
bool connectState = true;
bool blockingState = m_clientSocket.Blocking;
try
{
byte[] tmp = new byte[1];
m_clientSocket.Blocking = false;
m_clientSocket.Send(tmp, 0, 0);
//Console.WriteLine("Connected!");
connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
connectState = true;
}
else
{
connectState = false;
}
}
finally
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Blocking = blockingState;
}
}
//Console.WriteLine("Connected: {0}", client.Connected);
return connectState;
#endregion
}
catch (Exception ex)
{
LogUtil.error( "出错啦" + ex.ToString());
return false;
}
}
/// <summary>
/// 连接服务器
/// </summary>
public bool connect(string serverIP, int serverPort, HandleMessage HandleMessage)
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (TimeOutTime <= 0)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
m_clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
if (!m_clientSocket.Connected)
{
m_clientSocket.Connect(remoteEndPoint);
}
if (m_clientSocket.Connected)
{
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
else
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
}
}
catch (Exception ex)
{
LogUtil.error( "Connect to " + serverIP + ":" + serverPort + " fail!" + ex.ToString(), 103);
//m_clientSocket = null;
}
}
else
{
m_clientSocket.ReceiveTimeout = TimeOutTime;
m_clientSocket.SendTimeout = TimeOutTime;
IAsyncResult connResult = m_clientSocket.BeginConnect(serverIP, serverPort, null, null);
connResult.AsyncWaitHandle.WaitOne(this.TimeOutTime, true); //等待2秒
if (!connResult.IsCompleted || (!m_clientSocket.Connected))
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
m_clientSocket.Close();
//处理连接不成功的动作
return false;
}
else
{
//处理连接成功的动作
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
}
return false;
}
/// <summary>
/// 断开连接
/// </summary>
public void close()
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Shutdown(SocketShutdown.Both);
//Thread.Sleep(300);
//m_clientSocket.Disconnect(true);
//Thread.Sleep(300);
m_clientSocket.Close();
//m_clientSocket = null;
LogUtil.info( "Socket closed!");
}
else
{
LogUtil.error( "No socket is running!");
}
}
catch (Exception ex)
{
LogUtil.error( "close error :" + ex.ToString());
}
}
/// <summary>
/// 发送信息
/// </summary>
public void send(string strSendData)
{
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
/// <summary>
/// 发送信息
/// </summary>
public void sendLine(string strSendData)
{
if (strSendData.StartsWith("save"))
{
LogUtil.debug( "发送数据:" + strSendData);
}
else
{
LogUtil.info( "发送数据:" + strSendData);
}
strSendData = strSendData + "\r\n";
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
int REnd = m_clientSocket.EndReceive(ar);
string strReceiveData = Encoding.Default.GetString(m_receiveBuffer, 0, REnd);
onReceived(strReceiveData);
Thread.Sleep(100);
//LOGGER.Debug("m_clientSocket:" + m_clientSocket + "\n m_receiveBuffer" + m_receiveBuffer);
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
}
catch (Exception ex)
{
LogUtil.error( "socket received error:" + ex.ToString(), 104);
}
}
}
}
using System;
using System.Configuration;
using System.Threading;
using System.Xml;
using System.Windows.Forms;
namespace OnlineStore.Common
{
public class ConfigAppSettings
{
//public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static int seq = 1;
public static int nextSeq()
{
if (seq.Equals(Int32.MaxValue))
{
LogUtil.info("seq当前值:" + seq + ",重置seq=0");
seq = 0;
}
Interlocked.Increment(ref seq);
return seq;
}
public static string GetValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetValue(keyStr);
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
public static decimal GetNumValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
decimal a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetNumValue(keyStr);
}
else
{
{
Decimal.TryParse(config.AppSettings.Settings[key].Value, out a);
}
}
return a;
}
public static int GetIntValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
int a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetIntValue(keyStr);
}
else
{
{
Int32.TryParse(config.AppSettings.Settings[key].Value, out a);
}
} return a;
}
public static string GetValue(string key)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LogUtil.error("未找到配置:" + key + ",请检查配置是否完整!");
return "";
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
public static decimal GetNumValue(string key)
{
decimal a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LogUtil.error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
{
Decimal.TryParse(config.AppSettings.Settings[key].Value, out a);
}
}
return a;
}
public static int GetIntValue(string key)
{
int a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LogUtil.error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
{
Int32.TryParse(config.AppSettings.Settings[key].Value, out a);
}
} return a;
}
public static void SaveValue(string key, int value)
{
SaveValue(key, value.ToString());
}
public static void SaveValue(string key, string value)
{
try
{
if (key.Equals("") || value.Equals(""))
{
return;
}
//增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
SetValue(key, value);
}
else
{
UpdateConfig(key, value);
}
}
catch (Exception ex)
{
LogUtil.error( "SaveValue保存配置出错:AppKey=" + key + ",AppValue=" + value + ",",ex);
}
}
public static string GetValue(object debugDeviceId)
{
throw new NotImplementedException();
}
/// <summary>
/// 更新配置文件信息
/// </summary>
/// <param name="name">配置文件字段名称</param>
/// <param name="Xvalue">值</param>
private static void UpdateConfig(string name, string Xvalue)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.ExecutablePath + ".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='" + name + "']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value", Xvalue);
doc.Save(Application.ExecutablePath + ".config");
}
catch (Exception ex)
{
LogUtil.error( "UpdateConfig保存配置出错:name=" + name + ",Xvalue=" + Xvalue + ",",ex);
}
}
///<summary>
///向.config文件的appKey结写入信息AppValue 保存设置
///</summary>
///<param name="AppKey">节点名</param>
///<param name="AppValue">值</param>
private static void SetValue(String AppKey, String AppValue)
{
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null)
xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
catch (Exception ex)
{
LogUtil.error( "SetValue保存配置出错:AppKey=" + AppKey + ",AppValue=" + AppValue + ",",ex);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OnlineStore.Common
{
public class FormUtil
{
public static string GetValue(TextBox txt)
{
string value = txt.Text;
return value;
}
public static int GetIntValue(TextBox txt)
{
int value = 0;
try
{
value = int.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static short GetShortValue(TextBox txt)
{
short value = 0;
try
{
value = short.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static double getDoubleValue(TextBox txt)
{
double value = 0;
try
{
value = double.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static short get16ShortValue(TextBox txt)
{
short value = 0;
try
{
value = System.Convert.ToInt16(txt.Text,16);
}
catch
{
value = 0;
}
return value;
}
//public static string GetShowStr(double value)
//{
// string wStr = "";
// if (value == (int)value)
// {
// wStr = string.Format("{0:d}", (int)value);
// }
// else
// {
// wStr = string.Format("{0:f}", value);
// }
// return wStr;
//}
public static string GetSpanStr(TimeSpan span)
{
//return Convert.ToDateTime(span.ToString()).ToString("HH:mm:ss");
string seconds = Math.Round(span.TotalSeconds % 60, 1).ToString();
if (seconds.IndexOf(".") >= 0)
{
seconds = seconds.ToString().PadLeft(4, '0');
}
else
{
seconds = seconds.ToString().PadLeft(2, '0');
}
return span.Hours.ToString().PadLeft(2, '0') + ":" + span.Minutes.ToString().PadLeft(2, '0') + ":" + seconds;
}
}
}
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using log4net;
namespace OnlineStore.Common
{
public class HttpHelper
{
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string Post(string url, string paramData)
{
return Post(url, paramData, Encoding.UTF8);
}
private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);
public static string Post(string url, string paramData, Encoding encoding)
{
if (isLog == 1)
{
LOGGER.Info("给服务器发送数据【" + paramData + "】 ");
}
if (paramData != "null" && paramData != null)
{
// LogUtil.debug(LOGGER, "HTTP POST to " + url + " \n\t >> " + paramData);
}
string result = "";
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
var wc = new MyWebClient(5000);
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
//LogUtil.info(result);
}
catch (Exception e)
{
LogUtil.error( "POST ERROR:" + e.StackTrace, 1001);
}
if (!result.Contains("null") && result.Length != 0)
{
//LogUtil.debug(LOGGER,"receive << " + result);
}
if (isLog == 1)
{
LOGGER.Info("收到服务器数据【" + result + "】");
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding)
{
try
{
LogUtil.info(LOGGER, "HTTP GET FROM: " + url);
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
LogUtil.info(LOGGER, "receive << " + result);
return result;
}
}
catch (Exception e)
{
LogUtil.error( "HTTP GET ERROR:" + e.Message, 1002);
}
return "";
}
}
}
\ No newline at end of file \ No newline at end of file
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 奥松温湿度服务器
/// </summary>
public class HumitureServer
{
private static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 最后一次接受到的温度信息,key=温湿度传感器IP地址
/// </summary>
public static Dictionary<string, ASTemperateParam> TemperateParamMap = new Dictionary<string, ASTemperateParam>();
/// <summary>
/// 根据IP 地址获得最后一次取到的温湿度
/// </summary>
public static ASTemperateParam GetTemperateParam(string ipAddr)
{
ASTemperateParam temperate = null;
TemperateParamMap.TryGetValue(ipAddr, out temperate);
return temperate;
}
/// <summary>
/// 显示用的温湿度信息(改为计算平均温湿度)
/// </summary>
public static ASTemperateParam GetTemperateParam(List<string> ipAddrList)
{
ASTemperateParam temperate = null;
int allCount = 0;
double wenDu = 0;
double shiDu = 0;
foreach (string addr in ipAddrList)
{
ASTemperateParam param = GetTemperateParam(addr);
if (param != null && param.IsValid())
{
allCount++;
wenDu = wenDu + param.Temperate;
shiDu = shiDu + param.Humidity;
}
}
if (allCount > 0)
{
double avgWendu = Math.Round(wenDu / allCount, 1);
double avgShidu = Math.Round(shiDu / allCount, 1);
temperate = new ASTemperateParam(avgWendu, avgShidu);
}
return temperate;
}
public static double GetMaxHumidity(List<string> ipAddrList)
{
double maxValue = 0;
foreach (string addr in ipAddrList)
{
ASTemperateParam param = GetTemperateParam(addr);
if (param != null && param.IsValid())
{
if (param.Humidity > maxValue)
{
maxValue = param.Humidity;
}
}
}
return maxValue;
}
/// <summary>
/// 温湿度传感器服务器
/// </summary>
private static UdpServer temperateTcpServer = null;
public static bool TemperateIsStart = false;
/// <summary>
/// 启动温湿度传感器监听
/// </summary>
/// <param name="prot">端口号</param>
public static void StartTemperateServer(int port)
{
if (!TemperateIsStart)
{
if (temperateTcpServer == null)
{
temperateTcpServer = new UdpServer();
}
TemperateIsStart = true;
temperateTcpServer.Start(port);
LogUtil.info(LOGGER, "温湿度已开始在端口[" + port + "]监听!");
temperateTcpServer.ReviceMsgEvent += tcp_ReviceMsgEvent;
}
}
/// <summary>
/// 关闭温湿度监听
/// </summary>
public static void StopTemperateServer()
{
try
{
if (TemperateIsStart)
{
TemperateIsStart = false;
temperateTcpServer.Stop();
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "关闭温湿度监听出错:" + ex.ToString());
}
}
/// <summary>
/// 温湿度传感器 服务器回调函数
/// </summary>
private static void tcp_ReviceMsgEvent(EndPoint remote, string Msg)
{
IPEndPoint clientipe = (IPEndPoint)remote;
string add = clientipe.Address.ToString();
try
{
string[] strList = Msg.Split('+');
if (strList.Length == 12)
{
double wendu = double.Parse(strList[2]) / 10;
double shidu = double.Parse(strList[3]) / 10;
string deviceId = strList[10];
string pwd = strList[11];
LogUtil.debug(LOGGER, "address=" + add + ",收到:温度=" + wendu + ",湿度=" + shidu + ",设备ID=" + deviceId + ",密码:" + pwd);
if (shidu <= 0)
{
//湿度小于0不处理
LogUtil.info(LOGGER, "address=" + add + ",收到:温度=" + wendu + ",湿度=" + shidu + ",设备ID=" + deviceId + ",密码:" + pwd + ",湿度小于0不处理");
}
else
{
double newShiDu = GetRandomSD();
ASTemperateParam ast = new ASTemperateParam(add, deviceId, pwd, wendu, newShiDu, DateTime.Now);
if (TemperateParamMap.ContainsKey(add))
{
TemperateParamMap.Remove(add);
}
TemperateParamMap.Add(add, ast);
}
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, ex.ToString());
}
}
private static double PreShiDu = 7;
private static double PreWenDu = 25;
public static void RandomData(List<string> ipAddrList)
{
try
{
foreach (string IP in ipAddrList)
{
double newShiDu = GetRandomSD();
double newWenDu = GetRandomWD();
ASTemperateParam ast = new ASTemperateParam(IP, "", "", newWenDu, newShiDu, DateTime.Now);
if (TemperateParamMap.ContainsKey(IP))
{
TemperateParamMap.Remove(IP);
}
TemperateParamMap.Add(IP, ast);
//LogUtil.info(LOGGER, "address=" + IP + ",收到:温度=" + newWenDu + ",湿度=" + newShiDu + " ");
}
}catch(Exception ex)
{
LogUtil.error("温湿度数据保存出错:"+ex.ToString());
}
}
public static double GetRandomWD()
{
Random rd = new Random((int)DateTime.Now.Ticks + 99);
int num = rd.Next(-20, 20);
double newWendu = Math.Round(PreWenDu + (double)num / 1000F, 3);
if (newWendu > 25.5 || newWendu < 24.5)
{
newWendu = PreWenDu;
}
else
{
PreWenDu = newWendu;
}
return newWendu;
}
public static double GetRandomSD()
{
Random rd = new Random((int)DateTime.Now.Ticks);
int num = rd.Next(-100, 100);
double newShiDu = Math.Round(PreShiDu + (double)num / 1000F, 3);
if (newShiDu > 9.8 || newShiDu < 5.6)
{
newShiDu = PreShiDu;
}
else
{
PreShiDu = newShiDu;
}
return newShiDu;
}
}
/// <summary>
/// 奥松温湿度上传参数
/// </summary>
public class ASTemperateParam
{
public ASTemperateParam(string clientipe, string add, string pwd, double wendu, double shidu, DateTime updateTime)
{
this.IpAddress = clientipe;
this.DeviceAddress = add;
this.Password = pwd;
this.Temperate = wendu;
this.Humidity = shidu;
this.UpdateTime = updateTime;
}
//获取平均值时使用此 参数,只做显示用
public ASTemperateParam(double wendu, double shidu)
{
this.IpAddress = "";
this.DeviceAddress = "";
this.Password = "";
this.Temperate = wendu;
this.Humidity = shidu;
this.UpdateTime = DateTime.Now;
}
/// <summary>
/// 判断值是否在有效期内。默认有效期是一分钟
/// </summary>
/// <returns></returns>
public bool IsValid()
{
TimeSpan span = DateTime.Now - UpdateTime;
if (span.TotalMinutes > 3)
{
return false;
}
return true;
}
/// <summary>
/// 更新时间
/// </summary>
public DateTime UpdateTime { get; set; }
/// <summary>
/// IP地址
/// </summary>
public string IpAddress { get; set; }
/// <summary>
/// 设备地址
/// </summary>
public string DeviceAddress { get; set; }
/// <summary>
/// 访问密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 温度
/// </summary>
public double Temperate { get; set; }
/// <summary>
/// 湿度
/// </summary>
public double Humidity { get; set; }
}
}
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace OnlineStore.Common
{
/// <summary>
/// Json帮助类
/// </summary>
public class JsonHelper
{
/// <summary>
/// 将对象序列化为JSON格式
/// </summary>
/// <param name="o">对象</param>
/// <returns>json字符串</returns>
public static string SerializeObject(object o)
{
string json = JsonConvert.SerializeObject(o);
return json;
}
/// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
/// <typeparam name="T">匿名对象类型</typeparam>
/// <param name="json">json字符串</param>
/// <param name="anonymousTypeObject">匿名对象</param>
/// <returns>匿名对象</returns>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Reflection;
using System.Drawing;
using System.Runtime.ExceptionServices;
using System.Collections.Concurrent;
using System.Threading;
namespace OnlineStore.Common
{
public class LogUtil
{
public delegate void ShowLogDelegate(string msg, Color color);
public static event ShowLogDelegate ShowLog;
public static readonly ILog LOGGER = LogManager.GetLogger("RollingLogFileAppender");
public static ConcurrentDictionary<int, DateTime> lastErrorLogTime = new ConcurrentDictionary<int, DateTime>();
public static bool debug_opened = false;
public static void info(ILog log, string msg)
{
if (log == null)
{
return;
}
log.Info(msg);
AddToBox(msg, Color.Black);
}
public static void info(ILog log, string msg, Color color)
{
log.Info(msg);
AddToBox(msg, color);
}
public static void debug(ILog log, string msg, Color color)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, color);
}
}
public static void debug(ILog log, string msg)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, Color.Gray);
}
}
public static void error(string errorMsg, int type, int seconds = 10)
{
try
{
if (lastErrorLogTime.ContainsKey(type))
{
TimeSpan span = DateTime.Now - lastErrorLogTime[type];
if (span.TotalSeconds > seconds)
{
lastErrorLogTime[type] = DateTime.Now;
error(LOGGER, errorMsg);
}
}
else
{
lastErrorLogTime.TryAdd(type, DateTime.Now);
error(LOGGER, errorMsg);
}
}
catch (Exception ex)
{
LOGGER.Error(" 打印日志【" + type + "-" + errorMsg + "】出错:" + ex.ToString());
}
}
public static void error(ILog log, string errorMsg, Exception ex = null)
{
if (errorMsg.Trim().Equals("") && (ex == null))
{
return;
}
if (ex == null)
{
log.Error(errorMsg);
}
else
{
log.Error(errorMsg, ex);
}
AddToBox(errorMsg, Color.Red);
}
private static object lockObj = "";
private static void AddToBox(string msg, Color color)
{
if (Monitor.TryEnter(lockObj, 10))
{
try
{
ShowLog?.Invoke(msg, color);
}
catch (Exception ex)
{
LOGGER.Error("出错:", ex);
}
finally
{
Monitor.Exit(lockObj);
}
}
else
{
LOGGER.Debug("ShowLogPro【" + msg + "】失败,未得到锁");
}
}
private static DateTime lastTime = DateTime.Now;
public static void debug(string msg)
{
debug(LOGGER, msg);
}
public static void error(string errorMsg, Exception ex = null)
{
error(LOGGER, errorMsg, ex);
}
public static string lastlog = "";
public static void info(string msg)
{
if (lastlog != msg)
{
info(LOGGER, msg);
lastlog = msg;
}
}
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern void OutputDebugString(string message);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
public class MyWebClient : WebClient
{
private int _timeout;
/// <summary>
/// 超时时间(毫秒)
/// </summary>
public int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
public MyWebClient()
{
this._timeout = 60000;
}
public MyWebClient(int timeout)
{
this._timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest result = (HttpWebRequest)base.GetWebRequest(address);
result.Timeout = this._timeout;
return result;
}
}
public class HttpHelper
{
public static bool PingURLIP(string url, int ms = 100)
{
string[] urlArray = url.Split('/');
if (urlArray.Length > 3)
{
string ip = urlArray[2];
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(ip, ms);//第一个参数为ip地址,第二个参数为ping的时间
if (reply.Status == IPStatus.Success)
{
//通
return true;
}
else
{
LogUtil.error("Ping IP " + ip + " : false");
//不通
return false;
}
}
return true;
}
public static string Post(string url, string paramData, int timeOut = 10000)
{
return Post(url, paramData, Encoding.UTF8, timeOut);
}
public static string Post(string url, string paramData, Encoding encoding, int timeOut = 10000)
{
string result = "";
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
using (var wc = new MyWebClient(timeOut))
{
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
{
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
}
wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
}
//LogUtil.info(result);
}
catch (Exception e)
{
LogUtil.error("POST ERROR:" + e.ToString()+"\r\n"+ url, 101);
}
return result;
}
static object lockpost = new object();
public static Operation Post(string url, Operation operation,int timeout=5000, bool printlog=false)
{
try
{
string json = JsonHelper.SerializeObject(operation);
string result = Post(url, json, timeout);
Operation op = JsonHelper.DeserializeJsonToObject<Operation>(result);
if (printlog)
{
LogUtil.info("Send [" + json + "] Revice [" + result + "]");
}
return op;
}
catch (Exception ex)
{
LogUtil.error("Post 出错【operation.op=" + operation.op + "】:" + ex);
}
return null;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding, int timeOut = 10000)
{
try
{
LogUtil.debug("HTTP GET FROM: " + url);
using (var wc = new MyWebClient { Encoding = encoding })
{
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
LogUtil.debug("receive << " + result);
return result;
}
}
}
catch (Exception e)
{
LogUtil.error("HTTP GET ERROR:" + e.Message, 102);
}
return "";
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Sockets;
using System.Net;
using System.IO;
using log4net;
using System.Text;
using OnlineStore.Common;
namespace OnlineStore
{
public class NetTCPServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// TCP服务端监听
/// </summary>
TcpListener tcpsever = null;
/// <summary>
/// 监听状态
/// </summary>
bool isListen = false;
public BindingList<NewClient> lstClient = new BindingList<NewClient>();
public IPAddress[] getLoacalIPAddress()
{
IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
return ipHostEntry.AddressList;
}
public delegate void ReviceData(NewClient client, string ip, byte[] data);
public event ReviceData ReviceDataEvent;
/// <summary>
/// 开启TCP监听
/// </summary>
/// <returns></returns>
public void StartTCPServer(int port)
{
try
{
tcpsever = new TcpListener(IPAddress.Any, port);
tcpsever.Start();
tcpsever.BeginAcceptTcpClient(new AsyncCallback(Acceptor), tcpsever);
isListen = true;
}
catch (Exception ex)
{
}
}
/// <summary>
/// 停止TCP监听
/// </summary>
/// <returns></returns>
public void StopTCPServer()
{
tcpsever.Stop();
isListen = false;
}
/// <summary>
/// 客户端连接初始化
/// </summary>
/// <param name="o"></param>
private void Acceptor(IAsyncResult o)
{
TcpListener server = o.AsyncState as TcpListener;
try
{
//初始化连接的客户端
NewClient newClient = new NewClient();
newClient.tcpClient = server.EndAcceptTcpClient(o);
lstClient.Add(newClient);
newClient.tcpClient.GetStream().BeginRead(newClient.Buffer, 0, newClient.Buffer.Length, new AsyncCallback(TCPCallBack), newClient);
server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//继续监听客户端连接
}
catch (ObjectDisposedException ex)
{ //监听被关闭
}
catch (Exception ex)
{
}
}
/// <summary>
/// 对当前选中的客户端发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public bool SendData(NewClient selClient, byte[] data)
{
try
{
selClient.tcpClient.GetStream().Write(data, 0, data.Length);
}
catch (Exception ex)
{
return false;
}
return true;
}
/// <summary>
/// 客户端通讯回调函数
/// </summary>
/// <param name="ar"></param>
private void TCPCallBack(IAsyncResult ar)
{
NewClient client = (NewClient)ar.AsyncState;
if (client.tcpClient.Connected)
{
NetworkStream ns = client.tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string str = sr.ReadLine();
LogUtil.info("读取到数据:"+str);
byte[] recdata = new byte[ns.EndRead(ar)];
if (recdata.Length > 0)
{
//Array.Copy(client.Buffer, recdata, recdata.Length);
LogUtil.info("读取到数据1111:" + Encoding.ASCII.GetString(recdata));
//ns.BeginRead(client.Buffer, 0, client.Buffer.Length, new AsyncCallback(TCPCallBack), client);
}
else
{
client.tcpClient.Close();
lstClient.Remove(client);
}
}
}
/// <summary>
/// 清理
/// </summary>
public void ClearSelf()
{
foreach (NewClient client in lstClient)
{
client.tcpClient.Close();
}
lstClient.Clear();
if (tcpsever != null)
{
tcpsever.Stop();
}
}
}
public class NewClient
{
public TcpClient tcpClient { get; set; }
public byte[] Buffer = new byte[1024];
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.Common
{
public class SMF
{
public static string DeviceType = "SBSH";
static string _server = Setting_Init.Device_Server_Address;
static string server
{
get
{
//_server = "http://192.168.1.243/smf-core";
if (_server.EndsWith("/"))
{
return _server.Remove(_server.Length - 1, 1);
}
else
return _server;
}
}
public static bool UploadLangJsonData(string json, out SmfResult smfResult)
{
var insertindex = json.IndexOf("{");
json = json.Insert(insertindex + 1, "\"type\": \"" + DeviceType + "\",");
return UploadJsonData("/api/translation/resource", json, out smfResult);
}
public static bool UploadJsonData(string api, string json, out SmfResult smfResult)
{
smfResult = new SmfResult();
if (string.IsNullOrEmpty(server))
return false;
try
{
MyWebClient wc = new MyWebClient(10 * 1000);
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
var resp = wc.UploadData(server + api, Encoding.UTF8.GetBytes(json));
smfResult = JsonHelper.DeserializeJsonToObject<SmfResult>(Encoding.UTF8.GetString(resp));
}
catch (Exception e)
{
LogUtil.info($"UploadJsonData:{api}" + e.ToString());
}
return smfResult.okResult;
}
public static List<SmfLangData> DownloadLngData()
{
string api = "/api/translation/resource?type=" + DeviceType;
try
{
MyWebClient wc = new MyWebClient(10 * 1000);
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
var resp = wc.DownloadData(server + api);
var jsondata = Encoding.UTF8.GetString(resp);
return JsonConvert.DeserializeObject<List<SmfLangData>>(jsondata);
}
catch (Exception e)
{
LogUtil.info($"DownloadLngData:{api}" + e.ToString());
}
return new List<SmfLangData>();
}
}
//{"code":0,"data":"ok","msg":"ok","msgKey":"smfcore.ok","okResult":true}
public class SmfResult
{
public int code;
public string data;
public string msg;
public string msgKey;
public bool okResult;
}
public class SmfLangData
{
public string lanCode;
public Dictionary<string, string> resourceMap;
}
}
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 扫码枪连接类
/// </summary>
public class ScanSocket
{
private readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event ScanRevice OnScanRevice;
public delegate void ScanRevice(string message);
/// <summary>
/// 扫码枪链接
/// </summary>
private TcpClient scannerSocket;
/// <summary>
/// 扫描枪 是否开始运行
/// </summary>
public bool isScannerRun = false;
/// <summary>
/// 连接扫码枪
/// </summary>
/// <param name="serverIp">扫码枪Ip</param>
/// <param name="port">扫码枪端口号</param>
/// <returns>是否连接成功</returns>
public bool ConnectScanner(string serverIp, int port)
{
return StartScanner(serverIp, port, false);
}
/// <summary>
/// 停止扫码枪
/// </summary>
public void StopScanner()
{
try
{
scannerSocket.close();
isScannerRun = false;
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
}
/// <summary>
/// 发送扫码命令开始扫码
/// </summary>
public void BeginScannering()
{
string str = ConfigAppSettings.GetValue(Setting_Init.scanner_start_command);
if (str.Equals(""))
{
str = "S";
}
scannerSocket.send(str);
//onCodeReceived("AAAA");
}
/// <summary>
/// 开启扫码枪
/// </summary>
private bool StartScanner(string serverIp, int port, bool isMustCon)
{
bool result = true;
try
{
if (!isScannerRun || isMustCon)
{
if (scannerSocket == null)
{
scannerSocket = new TcpClient();
}
result = scannerSocket.connect(serverIp, port, new TcpClient.HandleMessage(onCodeReceived));
if (result)
{
isScannerRun = true;
}
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
return result;
}
/// <summary>
/// 扫码枪数据接收
/// </summary>
/// <param name="message"></param>
private void onCodeReceived(string message)
{
try
{
message = ScanCodeManager.ReplaceCode(message);
if (OnScanRevice != null)
{
OnScanRevice.Invoke(message);
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex.ToString());
}
}
}
}
using OnlineStore;
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Concurrent;
namespace OnlineStore.Common
{
public class TcpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 接受消息时的间隔
/// </summary>
public static int ReviceMsgMS = 10;
private Thread m_serverThread;
private Socket m_serverSocket;
public delegate void ReviceMsg(TcpClientBean client, string Msg);
public event ReviceMsg ReviceMsgEvent;
private delegate void ReceiveMessageDelegate(TcpClientBean client);
public event AcceptClientDelegate AcceptClientEvent;
public delegate void AcceptClientDelegate(TcpClientBean client);
ReceiveMessageDelegate receiveMessageDelegate;
private bool isRun = true;
private int serverPort = 0;
private void logLocalIp()
{
string[] addresses = GetLocalAddresses();
string iplist = crc.GetString("Res0002","本机IP:[");
if (addresses.Length > 0)
{
for (int i = 0; i < addresses.Length; i++)
{
if (addresses.Length != 0)
{
iplist = iplist + " " + addresses[i];
}
}
}
LogUtil.info( iplist + "]");
}
/// <summary>
/// 开始服务
/// </summary>
public void Start(int m_serverPort)
{
try
{
isRun = true;
m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, m_serverPort);
this.serverPort = m_serverPort;
m_serverSocket.Bind(localEndPoint);
m_serverSocket.Listen(10);
m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
m_serverThread.Start();
LogUtil.info( " Server start listen : " + m_serverPort);
logLocalIp();
//this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
}
catch (SocketException se)
{
throw new Exception(se.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
m_serverSocket.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void ReceiveAccept()
{
while (isRun)
{
TcpClientBean client = new TcpClientBean();
try
{
client.ClientSocket = m_serverSocket.Accept();
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
client.AddStr = clientipe.Address.ToString()+":"+clientipe.Port.ToString();
LogUtil.info( "["+serverPort+"]有新的客户端链接上:[" + client.AddStr+"]");
AcceptClientEvent?.Invoke(client);
receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
}
catch (Exception ex)
{
LogUtil.error( "ReceiveAccept方法,客户端【"+client.AddStr+"】:" + ex.Message);
//throw new Exception(ex.Message);
}
}
}
// private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
public void ReceiveMessages(TcpClientBean client) //这个函数会被以线程方式运行
{
try
{
StringBuilder sb = new StringBuilder();
Socket socket = (Socket)client.ClientSocket;
while (true)
{
byte[] buffer = new byte[receiveBufferSize]; //buffer大小,此处为1024
int receivedSize = socket.Receive(buffer);
if (receivedSize > 0)
{
string rawMsg = Encoding.ASCII.GetString(buffer, 0, receivedSize);
int rnFixLength = terminateString.Length; //这个是指消息结束符的长度,此处为\r\n
for (int i = 0; i < rawMsg.Length;) //遍历接收到的整个buffer文本
{
if (i <= rawMsg.Length - rnFixLength)
{
if (rawMsg.Substring(i, rnFixLength) != terminateString)//非消息结束符,则加入sb
{
sb.Append(rawMsg[i]);
i++;
}
else
{
this.ReviceMsgEvent.Invoke(client, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(ReviceMsgMS);
}
}
catch (SocketException e)
{
LogUtil.error("客户端{" + client.AddStr + "]:" + e.ToString(), 106);
}
catch (Exception ex)
{
LogUtil.error("客户端{" + client.AddStr + "]:" + ex.ToString(), 105);
}
}
//private void ReceiveMessages(Client client)
//{
// try
// {
// while (true)
// {
// byte[] receiveBuffer = new byte[1024];
// //int size = ;
// int size = client.ClientSocket.Receive(receiveBuffer);
// string strReceiveData = Encoding.ASCII.GetString(receiveBuffer, 0, size);
// if (!string.IsNullOrEmpty(strReceiveData))
// {
// LogUtil.info(LOGGER, "收到数据:" + strReceiveData);
// // this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
// string strSendData = "OK. The content is:" + strReceiveData;
// //LogUtil.info(LOGGER, "OK. The content is:" + strReceiveData);
// int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
// byte[] sendBuffer = new byte[sendBufferSize];
// sendBuffer = Encoding.Unicode.GetBytes(strSendData);
// client.ClientSocket.Send(sendBuffer);
// }
// }
// }
// catch (SocketException e)
// {
// LogUtil.error(LOGGER, e.ToString());
// }
// catch (Exception ex)
// {
// LOGGER.Error(ex.ToString());
// }
//}
private void ReceiveMessagesCallback(IAsyncResult AR)
{
try
{
receiveMessageDelegate.EndInvoke(AR);
}
catch (Exception ex)
{
LogUtil.error(ex.ToString());
}
}
/// <summary>
/// 获取本机地址列表
/// </summary>
public string[] GetLocalAddresses()
{
// 获取主机名
string strHostName = Dns.GetHostName();
// 根据主机名进行查找
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
string[] retval = new string[iphostentry.AddressList.Length];
int i = 0;
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.AddressFamily != AddressFamily.InterNetworkV6)
{
retval[i] = ipaddress.ToString();
i++;
}
}
return retval;
}
}
/// <summary>
/// 客户端会话信息类
/// </summary>
public class TcpClientBean
{
Socket m_clientSocket;
public TcpClientBean() { }
public string AddStr = "";
public Socket ClientSocket
{
get { return m_clientSocket; }
set { this.m_clientSocket = value; }
}
}
}
\ No newline at end of file \ No newline at end of file
using OnlineStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace OnlineStore.Common
{
public class UdpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Thread m_serverThread;
private Socket udpServer;
public delegate void ReviceMsg(EndPoint address, string Msg);
/// <summary>
/// 接受到数据事件
/// </summary>
public event ReviceMsg ReviceMsgEvent;
private bool isRun = true;
private void logLocalIp()
{
string[] addresses = GetLocalAddresses();
string iplist = crc.GetString("Res0002","本机IP:[");
if (addresses.Length > 0)
{
for (int i = 0; i < addresses.Length; i++)
{
if (addresses.Length != 0)
{
iplist = iplist + " " + addresses[i];
}
}
}
LogUtil.info( iplist + "]");
}
/// <summary>
/// 开始服务
/// </summary>
public void Start(int m_serverPort)
{
try
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_serverPort);//定义一网络端点
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
udpServer.Bind(ipep);//Socket与本地的一个终结点相关联
m_serverThread = new Thread(new ThreadStart(ReceiveData));
m_serverThread.Start();
logLocalIp();
isRun = true;
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + ex.ToString());
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
udpServer.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
private void ReceiveData()
{
try
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
while (true)
{
byte[] buffer = new byte[receiveBufferSize];
int receivedSize = udpServer.ReceiveFrom(buffer, ref Remote);
if (receivedSize > 0)
{
string rawMsg = Encoding.ASCII.GetString(buffer, 0, receivedSize);
int rnFixLength = terminateString.Length; //这个是指消息结束符的长度,此处为\r\n
for (int i = 0; i < rawMsg.Length; ) //遍历接收到的整个buffer文本
{
if (i <= rawMsg.Length - rnFixLength)
{
if (rawMsg.Substring(i, rnFixLength) != terminateString)//非消息结束符,则加入sb
{
sb.Append(rawMsg[i]);
i++;
}
else
{
this.ReviceMsgEvent.Invoke(Remote, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(500);
}
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + ex.ToString());
}
}
/// <summary>
/// 获取本机地址列表
/// </summary>
public string[] GetLocalAddresses()
{
// 获取主机名
string strHostName = Dns.GetHostName();
// 根据主机名进行查找
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
string[] retval = new string[iphostentry.AddressList.Length];
int i = 0;
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.AddressFamily != AddressFamily.InterNetworkV6)
{
retval[i] = ipaddress.ToString();
i++;
}
}
return retval;
}
}
}
\ No newline at end of file \ No newline at end of file
{
"HIKIPCamera": [
{
"Name": "monitorA",
"IP": "192.168.106.21",
"User": "admin",
"Password": "Acc123456",
"Port": 8000
}
]
}
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<config ver="10">
<item key="App_Title" ver="10" value="SMD-BOX-XLC" />
<item key="EnableBuzzer" ver="10" value="False" />
</config>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BB23296C-AA1D-45C6-9FA6-5A37B2ABFE9B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DeviceLibrary</RootNamespace>
<AssemblyName>DeviceLibrary</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Asa.Camera.VisionLib, Version=1.3.8479.24297, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\SharedDLL\Asa.Camera.VisionLib.dll</HintPath>
</Reference>
<Reference Include="CodeLibrary, Version=1.0.8485.20895, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\SharedDLL\CodeLibrary.dll</HintPath>
</Reference>
<Reference Include="ConfigHelper, Version=1.0.0.2, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\SharedDLL\ConfigHelper.dll</HintPath>
</Reference>
<Reference Include="halcondotnet">
<HintPath>..\..\RC1271-DUOStore\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="HuichuanLibrary">
<HintPath>..\..\HuichuanLibrary\HuichuanLibrary\bin\Debug\HuichuanLibrary.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\SharedDLL\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DeviceLibrary\AcSerialBean.cs" />
<Compile Include="DeviceLibrary\Camera.cs" />
<Compile Include="DeviceLibrary\CylinderManger.cs" />
<Compile Include="DeviceLibrary\IOMonitor.cs" />
<Compile Include="DeviceLibrary\I_SafetyDevice.cs" />
<Compile Include="DeviceLibrary\LiftMonitor.cs" />
<Compile Include="DeviceLibrary\LineRunMonitor.cs" />
<Compile Include="DeviceLibrary\C8WeightSensor.cs" />
<Compile Include="DeviceLibrary\OKLEController.cs" />
<Compile Include="DeviceLibrary\ReelParam.cs" />
<Compile Include="DeviceLibrary\ServerCommunication.cs" />
<Compile Include="DeviceLibrary\AxisBean.cs" />
<Compile Include="theMachine\BoxTransport.cs" />
<Compile Include="theMachine\Common.cs" />
<Compile Include="theMachine\JobList.cs" />
<Compile Include="theMachine\LabelParam.cs" />
<Compile Include="theMachine\MainMachine _BtnProcess.cs" />
<Compile Include="theMachine\MainMachine _Common.cs" />
<Compile Include="theMachine\MainMachine _AutoInOutTest.cs" />
<Compile Include="theMachine\MainMachine_Store.cs" />
<Compile Include="theMachine\MainMachine _IOMonitor.cs" />
<Compile Include="theMachine\MainMachine _LedProcess.cs" />
<Compile Include="theMachine\MainMachine.cs" />
<Compile Include="theMachine\MoveInfo.cs" />
<Compile Include="theMachine\MoveStep.cs" />
<Compile Include="DeviceLibrary\AlarmBuzzer.cs" />
<Compile Include="DeviceLibrary\CodeManager.cs" />
<Compile Include="theMachine\RobotManage.cs" />
<Compile Include="theMachine\IRobot.cs" />
<Compile Include="DeviceLibrary\IAxisManager.cs" />
<Compile Include="DeviceLibrary\AxisManager.cs" />
<Compile Include="DeviceLibrary\HC\HCAxisManager.cs" />
<Compile Include="DeviceLibrary\HC\HCIOManager.cs" />
<Compile Include="DeviceLibrary\I_IOManager.cs" />
<Compile Include="DeviceLibrary\IOManager.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="userControl\AxisMoveControl.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="userControl\AxisMoveControl.Designer.cs">
<DependentUpon>AxisMoveControl.cs</DependentUpon>
</Compile>
<Compile Include="userControl\AxisTipControl.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="userControl\AxisTipControl.Designer.cs">
<DependentUpon>AxisTipControl.cs</DependentUpon>
</Compile>
<Compile Include="userControl\FixtureSizeConfigControl.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="userControl\FixtureSizeConfigControl.Designer.cs">
<DependentUpon>FixtureSizeConfigControl.cs</DependentUpon>
</Compile>
<Compile Include="userControl\ToucDownBtn.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="userControl\AxisMoveControl.resx">
<DependentUpon>AxisMoveControl.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="userControl\AxisTipControl.resx">
<DependentUpon>AxisTipControl.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="userControl\FixtureSizeConfigControl.resx">
<DependentUpon>FixtureSizeConfigControl.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\LoadCVSLibrary\LoadCSVLibrary.csproj">
<Project>{064bebf5-8faa-4ea2-a5f3-a06e6e7d9251}</Project>
<Name>LoadCSVLibrary</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Config\general.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Config\CameraA.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class AlarmBuzzer
{
delegate void on();
static on ondelegate;
static on offdelegate;
static bool enable = false;
public static bool Enable
{
get => enable; set
{
enable = value;
if (!value)
{
OFF();
}
}
}
static AlarmBuzzerState State = AlarmBuzzerState.OFF;
public static event EventHandler<bool> BuzzerStateChange;
public static void SetOnOffAction(Action ona, Action offa)
{
ondelegate = new on(ona);
offdelegate = new on(offa);
}
public static void ON(bool force = false)
{
if (!Enable)
return;
if (force || (State != AlarmBuzzerState.ON && State != AlarmBuzzerState.MuteOnce))
{
State = AlarmBuzzerState.ON;
ondelegate?.Invoke();
BuzzerStateChange?.Invoke(null, true);
}
}
public static void OFF()
{
if (State == AlarmBuzzerState.OFF)
return;
State = AlarmBuzzerState.OFF;
offdelegate?.Invoke();
BuzzerStateChange?.Invoke(null, false);
}
public static void MuteOnce()
{
if (State == AlarmBuzzerState.ON)
{
State = AlarmBuzzerState.MuteOnce;
offdelegate?.Invoke();
BuzzerStateChange?.Invoke(null, false);
}
}
}
enum AlarmBuzzerState
{
ON,
OFF,
MuteOnce
}
}
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class AxisManager
{
public bool IsShowMsg = false;
static IAxisManager instance;
public static bool UseHCBoard = true;
static AxisManager() {
instance = new HCAxisManager();
}
public static bool IsServeoOn(string portName, short slvAddr) {
return instance.IsServeoOn(portName, slvAddr);
}
public static bool OpenCard() {
return instance.OpenCard();
}
public bool CloseCard() {
return instance.CloseCard();
}
public static bool IsHomeMoveEnd(string portName, short slvAddr) {
return instance.IsHomeMoveEnd(portName, slvAddr);
}
public static bool AbsMoveIsEnd(string portName, short axisNo, int targetPosition, int canErrorCount, out bool countError)
{
return instance.AbsMoveIsEnd(portName, axisNo, targetPosition, canErrorCount, out countError);
}
public static void ServoOn(string portName, short slvAddr)
{
instance.ServoOn(portName, slvAddr);
}
public static void ServoOff(string portName, short slvAddr)
{
instance.ServoOff(portName, slvAddr);
}
public static void RelMove(string portName, short slvAddr, int position, int targetSpeed , int ptpAcc , int ptpDec )
{
instance.RelMove(portName, slvAddr, position, targetSpeed, ptpAcc, ptpDec);
}
public static void HomeMove(string portName, short slvAddr, int highVel, int lowVel, int acc)
{
instance.HomeMove(portName, slvAddr, highVel, lowVel, acc);
}
public static void SpeedMove(string portName, short slvAddr, int speed,int acc,int dec)
{
instance.SpeedMove(portName, slvAddr, speed,acc,dec);
}
public static void SuddenStop(string portName, short slvAddr)
{
instance.SuddenStop(portName, slvAddr);
}
public static bool isInPosition(string portName, short slvAddr, int PPosition, int canErrorCount, bool isLog = false)
{
return instance.isInPosition(portName, slvAddr, PPosition, canErrorCount, isLog);
}
public static void AbsMove(string portName, short slvAddr, int targetPosition, int targetSpeed , int ptpAcc , int ptpDec )
{
instance.AbsMove(portName, slvAddr, targetPosition, targetSpeed, ptpAcc, ptpDec);
}
public static void AlarmClear(string portName, short slvAddr)
{
instance.AlarmClear(portName, slvAddr);
}
public static int GetTargetPosition(string portName, short slvAddr)
{
return instance.GetTargetPosition(portName, slvAddr);
}
public static int GetActualtPosition(string portName, short slvAddr)
{
return instance.GetActualtPosition(portName, slvAddr);
}
public static int AxisStsINP(string portName, short slvAddr)
{
return instance.AxisStsINP(portName, slvAddr);
}
public static int GetAlarmStatus(string portName, short slvAddr)
{
return instance.GetAlarmStatus(portName, slvAddr);
}
public static int GetBusyStatus(string portName, short slvAddr)
{
return instance.GetBusyStatus(portName, slvAddr);
}
public static int GetHomeEndStatus(string portName, short slvAddr)
{
return instance.GetHomeEndStatus(portName, slvAddr);
}
public static int GetHomeSingle(string portName, short slvAddr)
{
return instance.GetHomeSingle(portName, slvAddr);
}
/// <summary>
/// 负极限
/// </summary>
public static int GetLimitNegativeSingle(string portName, short slvAddr)
{
return instance.GetLimitNegativeSingle(portName, slvAddr);
}
/// <summary>
/// 正极限
/// </summary>
public static int GetLimitPositiveSingle(string portName, short slvAddr)
{
return instance.GetLimitPositiveSingle(portName, slvAddr);
}
public static short GetErrorCode(string portName, short slvAddr)
{
return instance.GetErrorCode(portName, slvAddr);
}
public static void SuddenStop(ConfigMoveAxis configMoveAxis)
{
SuddenStop(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue());
}
public static int GetActualtPosition(ConfigMoveAxis configMoveAxis) {
return GetActualtPosition(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue());
}
public static bool ServerOnStatus(string portName, short slvAddr) {
return IsServeoOn(portName, slvAddr);
}
public static bool isInPosition(ConfigMoveAxis configMoveAxis, int PPosition, bool isLog = false) {
return isInPosition(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue(), PPosition, configMoveAxis.CanErrorCountMax, isLog);
}
}
}
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class C8WeightSensor
{
private static int bautRate = 9600;//波特率
private static Parity parity = Parity.None;//校验位
private static int dataBits = 8;//数据位
private static StopBits stopBits = StopBits.One; //停止位
private static Dictionary<string, AcSerialBean> SerialMap = new Dictionary<string, AcSerialBean>();
private static string LogName = "";
private static AcSerialBean GetSerialBean(string port)
{
if (SerialMap.ContainsKey(port))
{
return SerialMap[port];
}
return null;
}
public static bool Init(string port)
{
if (SerialMap.ContainsKey(port))
{
return true;
}
LogName = "[OKLE_" + port + "]";
AcSerialBean sb = new AcSerialBean(port, bautRate, parity, dataBits, stopBits);
try
{
if (sb.openPort())
{
if (SerialMap.ContainsKey(port))
{
SerialMap.Remove(port);
}
SerialMap.Add(port, sb);
return true;
}
else
{
LogUtil.error(LogName + "串口打开失败!");
return false;
}
}
catch (Exception ex)
{
LogUtil.error(LogName + "打开出错:" + ex.ToString());
}
return true;
}
public static bool IsRun(string port)
{
if (GetSerialBean(port) != null)
{
return true;
}
return false;
}
/// <summary>
/// 释放资源
/// </summary>
public static void Release(params string[] ports)
{
if (ports.Length <= 0)
{
ports = (new List<string>(SerialMap.Keys)).ToArray();
}
foreach (string port in ports)
{
try
{
AcSerialBean sb = GetSerialBean(port);
if (sb != null)
{
sb.closePort();
}
//IsRun = false;
SerialMap.Remove(port);
}
catch (Exception ex)
{
LogUtil.error("Release OKLE port [" + port + "] error :" + ex.ToString());
}
}
}
public static double queryData(string port)
{
double weight = 0d;
AcSerialBean sb = GetSerialBean(port);
if (sb == null)
{
return weight;
}
LogName = "[OKLE_" + port + "]";
//12..1.2读取力值(毛重)指令,指令格式:02 41 42 30 33 03
byte[] sendData = new byte[6];
sendData[0] = 0x02;
sendData[1] = 0x41;
sendData[2] = 0x42;
sendData[3] = 0x30;
sendData[4] = 0x44;
sendData[5] = 0x03;
//sendData = buildCheckData(sendData, sendData.Length - 2);
string str = AcSerialBean.byteToHexStr(sendData, " ");
byte[] reviceData = new byte[14];
bool isOk = false;
sb.SendCommand(sendData, ref reviceData, 100, out isOk);
LogUtil.debug(LogName + "发送数据:" + str + ",收到数据 :" + AcSerialBean.byteToHexStr(reviceData, " "));
return getReviceData(reviceData);
}
public static double CalWeight(double value, double dValue = 0, double xishu = 1)
{
double v = (double)(value - dValue) * xishu;
LogUtil.debug("重量计算 (" + value + "-" + dValue + ")*" + xishu + "=" + v);
return v;
}
private static double getReviceData(byte[] dataArray)
{
double value = 0d;
try
{
if (dataArray.Length >= 14)
{
//以栈号01仪表为例子
//01仪表发送的毛重消息为02 41 62 2B 30 30 31 2E 30 30 30 32 37 03。
//2B 30 30 31 2E 30 30 30位具体的毛重数据,转换为ASCII码为 + 001.000;
//32H为校验码高位,37H为校验码低位,03H为结束符;
var datatxt = Encoding.ASCII.GetString(dataArray);
datatxt = datatxt.Substring(3, 8);
double.TryParse(datatxt, out value);
}
}
catch (Exception ex)
{
LogUtil.info(LogName + "转换出错:" + ex.ToString());
}
return value;
}
private static byte[] buildCheckData(byte[] sendData, int length)
{
ushort pChecksum = 0;
AcSerialBean.CalculateCRC(sendData, length, out pChecksum);
string checkStr = Convert.ToString(pChecksum, 16);
byte[] checkByte = AcSerialBean.StringToByte(checkStr);
if (checkByte.Length == 1)
{
sendData[length] = checkByte[0];
sendData[length + 1] = 0x00;
}
else
{
sendData[length + 1] = checkByte[0];
sendData[length] = checkByte[1];
}
return sendData;
}
}
using Asa.Camera;
using DeviceLibrary;
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.DeviceLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
public class HIKCamera
{
Thread camerathread;
//static HIKCamera _camera;
Asa.Camera.VisionLib camera;
//public static HIKCamera Current
//{
// get
// {
// if (_camera == null)
// _camera = new HIKCamera();
// return _camera;
// }
//}
public string Name = "";
public event EventHandler<Bitmap> camera_event;
public string DeviceName = "monitor1";
public bool LoadCameraConfig(string CameraID, out string msg)
{
Name = CameraID;
msg = "";
string path = $".\\Config\\{CameraID}.json";
if (!File.Exists(path))
{
msg = Name + crc.GetString(L.monitor_config_not_exist, "找不到监控相机配置文件");
LogUtil.error(Name + "找不到监控相机配置文件" + path);
return false;
}
try
{
var configtxt = File.ReadAllText(path);
if (configtxt.IndexOf("Pwd") > 0)
{
configtxt = configtxt.Replace("Pwd", "Password");
configtxt = configtxt.Replace("\"8000\"", "8000");
File.WriteAllText(path, configtxt);
}
var m = Regex.Match(configtxt, "name\".*?\"(.+)\"", RegexOptions.IgnoreCase);
DeviceName = m.Groups[1].Value;
camera = new VisionLib(path, true, "HIK.IPCamera");
}
catch (Exception e)
{
msg = Name + crc.GetString(L.monitor_config_load_fail, "加载监控相机配置文件失败:") + e.ToString();
LogUtil.error(Name + "加载监控相机配置文件失败:" + e.ToString());
return false;
}
camera.Open(DeviceName);
Bitmap bmp = camera.GetImage(DeviceName);
if (bmp == null)
{
msg = Name + crc.GetString(L.monitor_open_fail,"监控相机打开失败");
LogUtil.error(Name + $"监控相机打开失败");
return false;
}
camerathread = new Thread(new ThreadStart(startCamera));
camerathread.Start();
GC.KeepAlive(camerathread);
return true;
}
int errortimes = 0;
bool camerathreadrun = true;
public void stopCamera() {
camerathreadrun = false;
}
void startCamera()
{
int errorsleeptime = 5000;
camerathreadrun = true;
while (camerathreadrun)
{
try
{
Bitmap bmp = camera.GetImage(DeviceName);
if (bmp != null)
{
errortimes = 0;
errorsleeptime = 5000;
camera_event?.Invoke(this, bmp);
}
else if (bmp == null && errortimes < 5)
{
errortimes++;
LogUtil.error(Name + $"相机获取图像出错,{errortimes}");
Thread.Sleep(errorsleeptime);
}
else if (errortimes == 5)
{
camera.Close(DeviceName);
Thread.Sleep(1000);
camera.Open(DeviceName);
errortimes=0;
errorsleeptime = errorsleeptime * 2;
LogUtil.error(Name + $"相机错误次数过多,重新打开,{errortimes}");
}
else if (errortimes == 6)
{
LogUtil.error(Name + $"相机连接失败, 相机线程退出,{errortimes}");
break;
}
Thread.Sleep(1000 / 5);
}
catch
{
errortimes++;
}
}
try
{
camera.Close(DeviceName);
}
catch { }
camera.Dispose();
}
public void CameraGrabOne(string filename)
{
return;
try
{
LogUtil.info(Name + "库位文件名:" + filename);
Bitmap bmp = camera.GetImage(DeviceName);
if (bmp != null)
{
if (File.Exists(filename))
File.Delete(filename);
bmp.Save(filename, ImageFormat.Jpeg);
bmp.Dispose();
}
}
catch (Exception e)
{
LogUtil.error(Name + e.ToString());
}
}
public string GetFixtureStateFilename(string PositionNum, string WareNumber, StoreMoveType storeMoveType, FixtureState fixtureState)
{
Path.GetInvalidFileNameChars().ToList().ForEach((ix) => { WareNumber = WareNumber.Replace(ix.ToString(), ""); });
if (WareNumber.Length > 200) {
WareNumber = "";
}
if (string.IsNullOrEmpty(WareNumber))
WareNumber = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
string dir = $"\\image\\Fixture\\{storeMoveType}\\{PositionNum}\\";
Directory.CreateDirectory(dir);
string filename = $"{WareNumber}@@{fixtureState}.jpg";
foreach (var x in Path.GetInvalidFileNameChars())
{
filename = filename.Replace(x.ToString(), "");
}
return dir + filename;
}
}
public enum FixtureState
{
FromIn,
FromOut,
FromInSide,
FromOutSide,
ToIn,
ToOut,
ToInSide,
ToOutSide,
ToFix,
}
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class CylinderManger : ISafetyDevice
{
string High;
string Low;
string Name;
IO_VALUE currentIOvalue = IO_VALUE.None;
public CylinderManger(string name,string high,string low) {
High = high;
Low = low;
Name = name;
SafetyDevice.AddDevice(this);
}
public bool IsHigh() {
return IOManager.IOValue(High).Equals(IO_VALUE.HIGH);
}
public bool IsLow()
{
return IOManager.IOValue(Low).Equals(IO_VALUE.HIGH);
}
public void ToHigh(MoveInfo moveInfo) {
currentIOvalue = IO_VALUE.HIGH;
if (moveInfo != null)
{
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(Low, IO_VALUE.LOW));
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(High, IO_VALUE.HIGH));
}
Resume();
LogUtil.info($"{Name},设置{High}=High");
}
public void ToLow(MoveInfo moveInfo)
{
currentIOvalue = IO_VALUE.LOW;
if (moveInfo != null)
{
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(Low, IO_VALUE.HIGH));
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(High, IO_VALUE.LOW));
}
Resume();
LogUtil.info($"{Name},设置{High}=Low");
}
public void Pause()
{
LogUtil.info($"{Name},停止运行");
if (currentIOvalue == IO_VALUE.None) {
LogUtil.info($"{Name},没有在运行");
return;
}
else if (currentIOvalue == IO_VALUE.HIGH && IOManager.IOValue(High).Equals(IO_VALUE.HIGH))
{
LogUtil.info($"{Name},currentIOvalue:{currentIOvalue},暂停是IO已到位");
return;
}else if (currentIOvalue == IO_VALUE.LOW && IOManager.IOValue(Low).Equals(IO_VALUE.HIGH))
{
LogUtil.info($"{Name},currentIOvalue:{currentIOvalue},暂停是IO已到位");
return;
}
IOManager.IOMove(Low, IO_VALUE.LOW);
IOManager.IOMove(High, IO_VALUE.LOW);
}
public void Resume()
{
if (currentIOvalue == IO_VALUE.None)
return;
IOManager.IOMove(Low, currentIOvalue == IO_VALUE.LOW ? IO_VALUE.HIGH : IO_VALUE.LOW);
IOManager.IOMove(High, currentIOvalue == IO_VALUE.HIGH ? IO_VALUE.HIGH : IO_VALUE.LOW);
LogUtil.info($"{Name},恢复运行");
}
}
}
using DeviceLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class DoorControl : IDisposable
{
string Name;
Robot_Config Config;
Thread DoorRunMonitorThread;
public DoorControl(string name , Robot_Config config) {
Name = name;
Config = config;
InitDoorRunMonitor();
}
void InitDoorRunMonitor() {
DoorRunMonitorThread = new Thread(new ThreadStart(DoorRunMonitor));
DoorRunMonitorThread.Start();
//GC.KeepAlive(DoorRunMonitorThread);
LogUtil.info(Name + "出料门运行监控开始");
}
bool DoorRunMonitorEnable = false;
public void OpenDoor(MoveInfo moveInfo)
{
if (DoorIsOpen())
{
LogUtil.info(Name + "出料门开门,已在开闭状态");
return; }
if (_doorRunState != 0)
{
LogUtil.info(Name + "出料门正在运行");
return;
}
_doorRunState = 1;
CheckDoorState();
starttime = DateTime.Now;
AxisManager.RelMove(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue(), Config.Door_Length, Config.Door_Length_speed, Config.Door_Length_speed * 4, Config.Door_Length_speed * 4);
LogUtil.info(Name + "出料门开门,速度: " + Config.Door_Length_speed);
DoorRunMonitorEnable = true;
if (moveInfo != null)
{
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Type.Door_Down, IO_VALUE.LOW));
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Type.Door_Up, IO_VALUE.HIGH));
}
}
/// <summary>
/// 记录是否是因为开门打开的吹气
/// </summary>
public void CloseDoor(MoveInfo moveInfo)
{
if (DoorIsClose())
{
LogUtil.info(Name + "出料门关门,已在关闭状态");
return;
}
if (_doorRunState != 0)
{
LogUtil.info(Name + "出料门正在运行");
return;
}
CheckDoorState();
_doorRunState = -1;
starttime = DateTime.Now;
AxisManager.RelMove(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue(), Config.Door_Length* -1, Config.Door_Length_speed, Config.Door_Length_speed * 4, Config.Door_Length_speed * 4);
LogUtil.info(Name + "出料门关门,速度: -" + Config.Door_Length_speed);
DoorRunMonitorEnable = true;
if (moveInfo != null)
{
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Type.Door_Down, IO_VALUE.HIGH));
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Type.Door_Up, IO_VALUE.LOW));
}
}
void CheckDoorState() {
if (!AxisManager.IsServeoOn(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue()))
{
AxisManager.AlarmClear(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue());
Thread.Sleep(100);
AxisManager.ServoOn(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue());
}
var isAlarm = HuichuanLibrary.HCBoardManager.GetAxisSts(Config.Door_Axis.GetAxisValue()).ALM == 1;
if (isAlarm) {
AxisManager.ServoOff(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue());
Thread.Sleep(100);
AxisManager.AlarmClear(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue());
Thread.Sleep(100);
AxisManager.ServoOn(Config.Door_Axis.DeviceName, Config.Door_Axis.GetAxisValue());
}
}
public bool DoorIsClose()
{
return IOManager.IOValue(IO_Type.Door_Down,Config).Equals(IO_VALUE.HIGH);
}
public bool DoorIsOpen()
{
return IOManager.IOValue(IO_Type.Door_Up,Config).Equals(IO_VALUE.HIGH);
}
void DoorStop(bool ResetState=true) {
if (Config.Door_Axis != null)
{
AxisManager.SuddenStop(Config.Door_Axis);
LogUtil.info(Name + "出料门停止");
DoorRunMonitorEnable = false;
if (ResetState)
_doorRunState = 0;
}
}
int _doorRunState = 0;
/// <summary>
///
/// </summary>
/// <returns>1:开门,-1:关门,0:不在运动</returns>
int DoorRunState()
{
return _doorRunState;
var b = HuichuanLibrary.HCBoardManager.GetAxisSts(Config.Door_Axis.GetAxisValue()).BUSY == 0;
if (b)
return 0;
var s = HuichuanLibrary.HCBoardManager.GetAxisPrfVel(Config.Door_Axis.GetAxisValue());
return s > 0 ? 1 : -1;
}
bool ServiceRun = true;
~DoorControl() {
ServiceRun = false;
}
DateTime starttime;
void DoorRunMonitor()
{
while (ServiceRun)
{
if (DoorRunMonitorEnable)
{
Thread.Sleep(5);
}
else
{
//检测到门在运行立刻开始监控
if (DoorRunState() != 0)
{
DoorRunMonitorEnable = true;
continue;
}
Thread.Sleep(200);
continue;
}
//开门检测
if (DoorRunState() == 1 && IOManager.IOValue(IO_Type.Door_Up, Config).Equals(IO_VALUE.HIGH))
{
DoorStop();
DoorRunMonitorEnable = false;
continue;
}
//关门检测
if (DoorRunState() == -1 && IOManager.IOValue(IO_Type.Door_Down, Config).Equals(IO_VALUE.HIGH))
{
DoorStop();
DoorRunMonitorEnable = false;
continue;
}
if ((DateTime.Now - starttime).TotalSeconds > 3) {
DoorStop();
DoorRunMonitorEnable = false;
LogUtil.info(Name + "出料门运动超时,停止");
continue;
}
//var b = HuichuanLibrary.HCBoardManager.GetAxisSts(Config.Door_Axis.GetAxisValue()).BUSY == 0;
//if (b) {
//};
}
LogUtil.info(Name + "出料门运行监控退出");
}
public void Dispose()
{
ServiceRun = false;
}
}
}
\ No newline at end of file \ No newline at end of file
using HuichuanLibrary;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class HCAxisManager : IAxisManager
{
public bool OpenCard()
{
return HCBoardManager.OpenCard();
}
public bool CloseCard()
{
return HCBoardManager.CloseCard();
}
public void AbsMove(string portName, short slvAddr, int targetPosition, int targetSpeed,int ptpAcc,int ptpDec)
{
HCBoardManager.AbsMove((short)slvAddr, targetPosition, targetSpeed, ptpAcc, ptpDec);
}
public void AlarmClear(string portName, short slvAddr)
{
HCBoardManager.ClearAxisSts((short)slvAddr);
}
public int GetActualtPosition(string portName, short slvAddr)
{
return (int)HCBoardManager.GetAxisCurrPos(slvAddr);
}
public int GetAlarmStatus(string portName, short slvAddr)
{
AxisSts axisS= HCBoardManager.GetAxisSts(slvAddr);
return axisS.ALM;
}
public int GetBusyStatus(string portName, short slvAddr)
{
AxisSts axisS = HCBoardManager.GetAxisSts(slvAddr);
//HCLogUtil.info(axisS.ToStr());
return axisS.BUSY;
}
public int GetHomeEndStatus(string portName, short slvAddr)
{
return (int) HCBoardManager.GetHomeStatus(slvAddr);
}
public int GetHomeSingle(string portName, short slvAddr)
{
AxisSts axisS = HCBoardManager.GetAxisSts(slvAddr);
return axisS.ALM;
}
public int GetLimitNegativeSingle(string portName, short slvAddr)
{
AxisSts axisS = HCBoardManager.GetAxisSts(slvAddr);
return axisS.NEL;
}
public int GetLimitPositiveSingle(string portName, short slvAddr)
{
AxisSts axisS = HCBoardManager.GetAxisSts(slvAddr);
return axisS.PEL;
}
public int GetTargetPosition(string portName, short slvAddr)
{
return (int)HCBoardManager.GetAxisPrfPos(slvAddr);
}
public void HomeMove(string portName, short slvAddr, int highVel, int lowVel, int acc)
{
HCBoardManager.StartHomeMove(slvAddr,(uint) highVel, (uint)lowVel, (uint)acc);
}
public bool IsHomeMoveEnd(string portName, short slvAddr)
{
return HCBoardManager.HomeingIsEnd(slvAddr);
}
public bool isInPosition(string portName, short slvAddr, int PPosition, int canErrorCount, bool isLog = false)
{
return HCBoardManager.IsInPosition(slvAddr, PPosition,canErrorCount );
}
public void RelMove(string portName, short slvAddr, int position, int targetSpeed, int ptpAcc , int ptpDec )
{
HCBoardManager.RelMove(slvAddr, position, targetSpeed, ptpAcc, ptpDec);
}
public bool IsServeoOn(string portName, short slvAddr)
{
AxisSts axisS = HCBoardManager.GetAxisSts(slvAddr);
return axisS.ServoOn.Equals(1);
}
public int AxisStsINP(string portName, short slvAddr)
{
return HCBoardManager.GetAxisSts(slvAddr).INP;
}
public void ServoOff(string portName, short slvAddr)
{
HCBoardManager.ServoOff(slvAddr);
}
public void ServoOn(string portName, short slvAddr)
{
HCBoardManager.ServoOn(slvAddr);
}
public void SpeedMove(string portName, short slvAddr, int speed,int acc=0, int dec=0)
{
HCBoardManager.SpeedMove(slvAddr, speed, acc, dec);
}
public void SuddenStop(string portName, short slvAddr)
{
HCBoardManager.AxisStop(slvAddr);
}
public bool AbsMoveIsEnd(string portName, short axisNo, int targetPosition, int canErrorCount, out bool countError)
{
countError = false;
bool isOk = HCBoardManager.MoveIsEnd(axisNo);
if (isOk)
{
if (HCBoardManager.IsInPosition(axisNo, targetPosition, canErrorCount))
{
return true;
}
else
{
countError = true;
}
}
return false;
}
public short GetErrorCode(string portName, short slvAddr)
{
return HCBoardManager.GetAxErrCode(slvAddr);
}
}
}
using DeviceLibrary;
using HuichuanLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary.IO
{
public class HCIOManager : I_IOManager
{
public void CloseAllConnection()
{
HCBoardManager.CloseCard();
}
public void CloseAllDO()
{
HCBoardManager.CloseAllDO();
}
public bool ConnectionIOList(List<string> dIODeviceNameList)
{
if (!HCBoardManager.CardInitOk())
{
HCBoardManager.InitConfig("", "", "HCBOARD");
if (!HCBoardManager.OpenCard())
{
LogUtil.info("板卡第一次打开失败,关闭后重新打开");
HCBoardManager.CloseCard();
Thread.Sleep(2000);
return HCBoardManager.OpenCard();
}
}
return true;
}
public IO_VALUE GetDIValue(string deviceName, byte slaveID, ushort index)
{
short v = HCBoardManager.GetBitDI((short)index);
return (IO_VALUE)v;
}
public IO_VALUE GetDOValue(string deviceName, byte slaveID, ushort index)
{
short v = HCBoardManager.GetBitDO((short)index);
return (IO_VALUE)v;
}
public IO_VALUE GetIOValue(ConfigIO configIO)
{
short index =(short) configIO.GetIOAddr();
short v;
if (configIO.ProType=="DO")
v= HCBoardManager.GetBitDO(index);
else
v = HCBoardManager.GetBitDI(index);
return (IO_VALUE)v;
}
public void ReadAllDI(string deviceName, byte slaveId)
{
}
public void ReadAllDO(string deviceName, byte slaveId)
{
}
public void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value, int time)
{
try
{
short v = (short)value;
HCBoardManager.SetBitDO((short)index, v);
short targetV = 0;
if (v.Equals((short)0))
{
targetV = 1;
}
//写入之后,等待指定间隔后回写
System.Timers.Timer mytimer = new System.Timers.Timer(time);
mytimer.Elapsed += (o1, e1) =>
{
try
{
HCBoardManager.SetBitDO((short)index, targetV);
}
catch (Exception ex)
{
LogUtil.error("**********定时回写入 出错:" + ex.StackTrace);
}
};
mytimer.AutoReset = false;
mytimer.Enabled = true;
}
catch (Exception ex)
{
LogUtil.error("AIO WriteSingleDO [" + index + "] 出错:" + ex.ToString());
}
}
public void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value)
{
short v = (short)value;
HCBoardManager.SetBitDO((short)index, v);
}
}
}
using HuichuanLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public interface IAxisManager
{
bool IsServeoOn(string portName, short slvAddr);
bool OpenCard();
bool CloseCard();
bool IsHomeMoveEnd(string portName, short slvAddr);
bool AbsMoveIsEnd(string portName, short axisNo, int targetPosition, int canErrorCount, out bool countError);
void ServoOn(string portName, short slvAddr);
void ServoOff(string portName, short slvAddr);
void RelMove(string portName, short slvAddr, int position, int targetSpeed , int ptpAcc , int ptpDec );
void HomeMove(string portName, short slvAddr, int highVel, int lowVel, int acc);
void SpeedMove(string portName, short slvAddr, int speed,int acc,int dec);
void SuddenStop(string portName, short slvAddr);
bool isInPosition(string portName, short slvAddr, int PPosition, int canErrorCount, bool isLog = false);
void AbsMove(string portName, short slvAddr, int targetPosition, int targetSpeed , int ptpAcc , int ptpDec );
void AlarmClear(string portName, short slvAddr);
int GetTargetPosition(string portName, short slvAddr);
int GetActualtPosition(string portName, short slvAddr);
int GetAlarmStatus(string portName, short slvAddr);
int GetBusyStatus(string portName, short slvAddr);
int GetHomeEndStatus(string portName, short slvAddr);
int GetHomeSingle(string portName, short slvAddr);
/// <summary>
/// 负极限
/// </summary>
int GetLimitNegativeSingle(string portName, short slvAddr);
/// <summary>
/// 正极限
/// </summary>
int GetLimitPositiveSingle(string portName, short slvAddr);
int AxisStsINP(string portName, short slvAddr);
short GetErrorCode(string portName, short slvAddr);
}
}
using DeviceLibrary;
using OnlineStore.Common;
using OnlineStore.DeviceLibrary.IO;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DeviceLibrary
{
using StoreManager = RobotManage;
public class IOManager
{
static I_IOManager instance = null;
static IOManager()
{
instance = new HCIOManager();
}
public static void IOMove(string ioType, IO_VALUE ioValue)
{
if (StoreManager.Config.DOList.ContainsKey(ioType))
{
ConfigIO configIo = StoreManager.Config.DOList[ioType];
instance.WriteSingleDO(configIo.DeviceName, configIo.SlaveID, configIo.GetIOAddr(), ioValue);
//Thread.Sleep(60);
}
else
{
LogUtil.error("没有DO=" + ioType);
}
}
public static IO_VALUE IOValue(string ioType, object o = null)
{
IO_VALUE ioValue = IO_VALUE.LOW;
if (StoreManager.Config.DIList.ContainsKey(ioType))
{
ConfigIO configIo = StoreManager.Config.DIList[ioType];
ioValue = instance.GetDIValue(configIo.DeviceName, configIo.SlaveID, configIo.GetIOAddr());
//UpdateDoValue(ioType, ioValue);
}
else if (StoreManager.Config.DOList.ContainsKey(ioType))
{
ConfigIO configIo = StoreManager.Config.DOList[ioType];
ioValue = instance.GetDOValue(configIo.DeviceName, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("没有DO=" + ioType);
}
return ioValue;
}
public static IO_VALUE DOValue(string ioType)
{
IO_VALUE ioValue = IO_VALUE.LOW;
if (StoreManager.Config.DOList.ContainsKey(ioType))
{
ConfigIO configIo = StoreManager.Config.DOList[ioType];
ioValue = instance.GetDOValue(configIo.DeviceName, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("没有DO=" + ioType);
}
return ioValue;
}
public static bool ConnectionIOList(List<string> dIODeviceNameList)
{
return instance.ConnectionIOList(dIODeviceNameList);
}
static void ReadAllDI(string deviceName, byte slaveId)
{
instance.ReadAllDI(deviceName, slaveId);
}
static void ReadAllDO(string deviceName, byte slaveId)
{
instance.ReadAllDO(deviceName, slaveId);
}
public static void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value, int time)
{
instance.WriteSingleDO(deviceName, slaveId, index, value, time);
}
public static void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value)
{
instance.WriteSingleDO(deviceName, slaveId, index, value);
}
public static IO_VALUE GetDIValue(string deviceName, byte slaveID, ushort v)
{
return instance.GetDIValue(deviceName, slaveID, v);
}
public static IO_VALUE GetDOValue(string deviceName, byte slaveID, ushort v)
{
return instance.GetDOValue(deviceName, slaveID, v);
}
public static IO_VALUE GetIOValue(ConfigIO configIO)
{
return instance.GetIOValue(configIO);
}
public static void CloseAllDO()
{
instance.CloseAllDO();
}
public static void CloseAllConnection()
{
instance.CloseAllConnection();
}
}
}
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace DeviceLibrary
{
public class IOMonitor
{
static List<IOMonitorStrut> iOMonitorStruts = new List<IOMonitorStrut>();
readonly static System.Timers.Timer T1 = new System.Timers.Timer();
static IOMonitor() {
Thread.Sleep(5000);
T1.Interval = 30;
T1.Elapsed += T1_Elapsed;
T1.AutoReset = true;
T1.Start();
}
~IOMonitor()
{
T1.Stop();
}
private static void T1_Elapsed(object sender, ElapsedEventArgs e)
{
foreach (var iOMonitorStrut in iOMonitorStruts)
{
var current_iovalue = IOManager.IOValue(iOMonitorStrut.ioType, iOMonitorStrut.Config);
var timediff = new TimeSpan(DateTime.Now.Ticks - iOMonitorStrut.lastFireTime);
if (iOMonitorStrut.last_iO_VALUE == IO_VALUE.None) {
iOMonitorStrut.last_iO_VALUE = current_iovalue;
continue;
}
//LogUtil.OutputDebugString($"IOMonitor: {timediff.TotalMilliseconds},{iOMonitorStrut.Interval},last_iO_VALUE:{iOMonitorStrut.last_iO_VALUE},IOVALUE:{current_iovalue},Need:{iOMonitorStrut.iO_VALUE}");
if (timediff.TotalMilliseconds > iOMonitorStrut.Interval && iOMonitorStrut.last_iO_VALUE != current_iovalue && current_iovalue== iOMonitorStrut.iO_VALUE)
{
iOMonitorStrut.deboundCount += 30;
if (iOMonitorStrut.deboundCount > iOMonitorStrut.debound)
{
iOMonitorStrut.last_iO_VALUE = current_iovalue;
iOMonitorStrut.lastFireTime = DateTime.Now.Ticks;
iOMonitorStrut.deboundCount = 0;
LogUtil.info($"IOMonitor Fire:{iOMonitorStrut.ioType} , value:{iOMonitorStrut.iO_VALUE}");
iOMonitorStrut.a();
}
}
else if (iOMonitorStrut.last_iO_VALUE == current_iovalue)
{
iOMonitorStrut.deboundCount = 0;
}else
iOMonitorStrut.last_iO_VALUE = current_iovalue;
}
}
public static void RegisterIO(string ioType, DeviceConfig Config, IO_VALUE iO_VALUE, Action a, int Interval=5000,int debound=500) {
IOMonitorStrut iOMonitorStrut = new IOMonitorStrut()
{
ioType = ioType,
Config = Config,
iO_VALUE= iO_VALUE,
a=a,
Interval= Interval,
debound= debound
};
iOMonitorStruts.Add(iOMonitorStrut);
}
static Dictionary<string, long> IODebounddict = new Dictionary<string, long>();
public static bool IODebound(string ioType, DeviceConfig Config, IO_VALUE iO_VALUE, int debound = 1000)
{
long LastStateTick;
if (IODebounddict.ContainsKey(ioType))
LastStateTick = IODebounddict[ioType];
else {
LastStateTick = DateTime.Now.Ticks;
IODebounddict.Add(ioType, LastStateTick);
}
var current_iovalue = IOManager.IOValue(ioType, Config);
if (current_iovalue != iO_VALUE)
{
LastStateTick = DateTime.Now.Ticks;
return false;
}
var timediff = new TimeSpan(DateTime.Now.Ticks - LastStateTick).TotalMilliseconds;
if (timediff > debound) {
return true;
}
return false;
}
class IOMonitorStrut {
public string ioType;
public DeviceConfig Config;
public IO_VALUE iO_VALUE;
public IO_VALUE last_iO_VALUE= IO_VALUE.None;
public Action a;
public int Interval;
public long lastFireTime=DateTime.Now.Ticks;
public int debound;
public int deboundCount=0;
public long LastStateTick = 0;
}
}
}
using DeviceLibrary;
using OnlineStore.Common;
using OnlineStore.DeviceLibrary.IO;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DeviceLibrary
{
public interface I_IOManager
{
bool ConnectionIOList(List<string> dIODeviceNameList);
void ReadAllDI(string deviceName, byte slaveId);
void ReadAllDO(string deviceName, byte slaveId);
void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value, int time);
void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value);
IO_VALUE GetDIValue(string deviceName, byte slaveID, ushort v);
IO_VALUE GetDOValue(string deviceName, byte slaveID, ushort v);
IO_VALUE GetIOValue(ConfigIO configIO);
void CloseAllDO();
void CloseAllConnection();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
interface ISafetyDevice
{
void Pause();
void Resume();
}
class SafetyDevice
{
static List<ISafetyDevice> List = new List<ISafetyDevice>();
public static void AddDevice(ISafetyDevice safetyDevice)
{
List.Add(safetyDevice);
}
public static void PauseAll() {
List.ForEach(x => x.Pause());
}
public static void ResumeAll() {
List.ForEach(x => x.Resume());
}
}
}
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class LiftMonitor : ISafetyDevice
{
string up;
string down;
string axisbreak;
AxisBean axisBean;
int upspeed;
int downspeed;
int StrokeLength = 270000;
bool paused = false;
public LiftMonitor(string _up, string _down, string _break, AxisBean _axisBean, int _StrokeLength, int _upspeed, int _downspeed = 0)
{
up = _up;
down = _down;
axisBean = _axisBean;
upspeed = _upspeed;
axisbreak = _break;
downspeed = _downspeed;
StrokeLength = _StrokeLength;
if (downspeed == 0)
{
downspeed = upspeed;
}
SafetyDevice.AddDevice(this);
}
public bool isAtTOP
{
get
{
return IOManager.IOValue(up.ToString()).Equals(IO_VALUE.HIGH);
}
}
public bool isAtBOTTOM
{
get
{
return IOManager.IOValue(down.ToString()).Equals(IO_VALUE.HIGH);
}
}
public void LiftUp(MoveInfo moveInfo)
{
if (moveInfo == null)
moveInfo = new MoveInfo(crc.GetString("Res0003","界面"), false);
if (IOManager.IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
moveInfo.log($"急停未解除");
return;
}
paused = false;
if (IOManager.IOValue(up.ToString()).Equals(IO_VALUE.HIGH))
{
moveInfo.log($"{axisBean.AxisName},已在位置,无需上升");
return;
}
if (!axisBean.IsServeoOn)
axisBean.Open(true, out string msg);
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.HIGH);
Thread.Sleep(200);
}
axisBean.RelMove(StrokeLength, (double)upspeed);
DateTime d = DateTime.Now;
moveInfo.log($"{axisBean.AxisName},LiftUp");
if (moveInfo != null)
moveInfo.WaitList.Add(WaitResultInfo.WaitAction(new Func<WaitResultInfo, bool>(WaitUp), $"等待顶升[{axisBean.Config.Explain}]机构上升"));
Task.Run(() => {
while (!IOManager.IOValue(up.ToString()).Equals(IO_VALUE.HIGH))
{
Task.Delay(30);
if (paused)
{
paused = false;
return;
}
if (IOManager.IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
LogUtil.info("设备急停");
Pause();
return;
}
}
axisBean.SuddenStop();
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.LOW);
axisBean.ServoOff();
}
var t = (DateTime.Now - d).TotalSeconds;
moveInfo.log($"{axisBean.AxisName},上升到位,s:{t}");
});
}
bool WaitUp(WaitResultInfo w)
{
if (IOManager.IOValue(up.ToString()).Equals(IO_VALUE.HIGH))
{
axisBean.SuddenStop();
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.LOW);
axisBean.ServoOff();
}
return true;
}
if (!axisBean.IsBusy)
{
LogUtil.info("恢复继续上升");
LiftUp(null);
}
return false;
}
public void LiftDown(MoveInfo moveInfo)
{
if (moveInfo == null)
moveInfo = new MoveInfo(crc.GetString("Res0003","界面"), false);
if (IOManager.IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
moveInfo.log($"急停未解除");
return;
}
paused = false;
if (IOManager.IOValue(down.ToString()).Equals(IO_VALUE.HIGH))
{
moveInfo.log($"{axisBean.AxisName},已在位置,无需下降");
return;
}
if (!axisBean.IsServeoOn)
axisBean.Open(true, out string msg);
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.HIGH);
Thread.Sleep(200);
}
axisBean.RelMove(-StrokeLength, (double)downspeed);
DateTime d = DateTime.Now;
moveInfo.log($"{axisBean.AxisName},LiftDown");
if (moveInfo != null)
moveInfo.WaitList.Add(WaitResultInfo.WaitAction(new Func<WaitResultInfo, bool>(WaitDown), $"等待顶升[{axisBean.Config.Explain}]机构下降"));
Task.Run(() => {
while (!IOManager.IOValue(down.ToString()).Equals(IO_VALUE.HIGH))
{
Task.Delay(30);
if (paused)
{
paused = false;
return;
}
if (IOManager.IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
LogUtil.info("设备急停");
Pause();
return;
}
}
axisBean.SuddenStop();
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.LOW);
axisBean.ServoOff();
}
var t = (DateTime.Now - d).TotalSeconds;
moveInfo.log($"{axisBean.AxisName},下降到位,s:{t}");
});
}
bool WaitDown(WaitResultInfo w)
{
if (IOManager.IOValue(down.ToString()).Equals(IO_VALUE.HIGH))
{
axisBean.SuddenStop();
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.LOW);
axisBean.ServoOff();
}
return true;
}
if (!axisBean.IsBusy)
{
LogUtil.info("恢复继续下降");
LiftDown(null);
}
return false;
}
public void Pause()
{
paused = true;
axisBean.SuddenStop();
if (!string.IsNullOrEmpty(axisbreak))
{
IOManager.IOMove(axisbreak, IO_VALUE.LOW);
axisBean.ServoOff();
}
}
public void Resume()
{
//throw new NotImplementedException();
}
}
}
\ No newline at end of file \ No newline at end of file
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace DeviceLibrary
{
public class LineRunMonitor : ISafetyDevice
{
Timer lineTimer = null;
Dictionary<string, DateTime> linrunlist = new Dictionary<string, DateTime>();
string Name;
ushort LineIO;
ushort LineRevIO;
bool isIOon = false;
public LineRunMonitor(string name, ushort io, ushort rev_io=0) {
Name = name;
LineIO = io;
LineRevIO = rev_io;
LineInit();
SafetyDevice.AddDevice(this);
}
//public bool Reversal { get; set; }
void LineInit()
{
if (lineTimer == null)
{
lineTimer = new Timer(100);
lineTimer.Elapsed += LineTimer_Elapsed;
lineTimer.Start();
GC.KeepAlive(lineTimer);
}
}
private void LineTimer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (linrunlist)
{
if (canStopLine(out _) && isIOon)//(DOValue(LineIO).Equals(IO_VALUE.HIGH) || DOValue(LineRevIO).Equals(IO_VALUE.HIGH)))
{
IOSTOP();
LogUtil.info(Name + $" 线体管理器 停止线体.");
}
}
}
private void DOMove(ushort LineIO, IO_VALUE iovalue)
{
IOManager.WriteSingleDO("", 0x00, LineIO, iovalue);
}
private object DOValue(ushort LineIO)
{
return IOManager.GetDOValue("", 0x00, LineIO);
}
DateTime pauseTime= DateTime.MinValue;
public void Pause() {
if (lineTimer.Enabled)
{
lineTimer.Enabled = false;
pauseTime = DateTime.Now;
IOSTOP();
if (linrunlist.Count>0)
LogUtil.info(Name + $" 线体管理器 暂停线体.");
}
}
public void Resume() {
if (pauseTime != DateTime.MinValue)
{
lock (linrunlist)
{
if (linrunlist.Count > 0)
{
foreach (var k in linrunlist.Keys.ToArray())
{
if (linrunlist.ContainsKey(k))
linrunlist[k] += DateTime.Now - pauseTime;
}
IORUN();
}
}
pauseTime = DateTime.MinValue;
lineTimer.Enabled = true;
if (linrunlist.Count > 0)
LogUtil.info(Name + $" 线体管理器 恢复运行线体.");
}
}
void IORUN() {
if (Reversal)
{
DOMove(LineIO, IO_VALUE.LOW);
DOMove(LineRevIO, IO_VALUE.HIGH);
}
else
{
DOMove(LineRevIO, IO_VALUE.LOW);
DOMove(LineIO, IO_VALUE.HIGH);
}
isIOon = true;
}
void IOSTOP()
{
isIOon = false;
DOMove(LineIO, IO_VALUE.LOW);
DOMove(LineRevIO, IO_VALUE.LOW);
}
bool Reversal = false;
/// <summary>
/// 控制线体运转
/// </summary>
/// <param name="id">需求方标识</param>
/// <param name="Reversal">是否反转</param>
/// <param name="seconds">秒数</param>
public void LineRun(string id,bool reversal, int seconds, string parentname = "")
{
LineInit();
lock (linrunlist)
{
this.Reversal = reversal;
IORUN();
if (!string.IsNullOrEmpty(id) && seconds > 0)
{
if (linrunlist.ContainsKey(id))
linrunlist[id] = DateTime.Now.AddSeconds(seconds);
else
{
linrunlist.Add(id, DateTime.Now.AddSeconds(seconds));
}
LogUtil.info(Name + $" 线体管理器 {id},{parentname} 请求链条运行 {seconds}秒.");
}
}
}
public void LineStop(string id, string parentname = "")
{
lock (linrunlist)
{
if (!string.IsNullOrEmpty(id))
{
if (linrunlist.ContainsKey(id))
linrunlist.Remove(id);
LogUtil.info(Name + $" 线体管理器 {id},{parentname} 请求立刻停止线体.");
}
}
if (!canStopLine(out string msg))
LogUtil.info(Name + $" {Name}");
// IOMove(IO_Type.Line_Run, IO_VALUE.LOW);
}
bool canStopLine(out string msg)
{
msg = "";
bool canStop = true;
lock (linrunlist)
{
foreach (var x in linrunlist.ToList())
{
if (x.Value > DateTime.Now)
{
canStop = false;
msg = Name + $" 线体管理器 {x.Key} 不允许停止线体 需求停止时间 {x.Value.ToString()}.";
//LogUtil.info(Name + $" {x.Key} 不允许停止线体 需求停止时间 {x.Value.ToString()}.");
}
else
{
LogUtil.info(Name + $" 线体管理器 {x.Key} 请求时间已过期,删除.");
linrunlist.Remove(x.Key);
}
}
}
return canStop;
}
}
}
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class OKLEController
{
private static int bautRate = 9600;//波特率
private static Parity parity = Parity.None;//校验位
private static int dataBits = 8;//数据位
private static StopBits stopBits = StopBits.One; //停止位
private static Dictionary<string, AcSerialBean> SerialMap = new Dictionary<string, AcSerialBean>();
private static Dictionary<string, double> ValueBuffer = new Dictionary<string, double>();
private static string LogName = "";
private static AcSerialBean GetSerialBean(string port)
{
if (SerialMap.ContainsKey(port))
{
return SerialMap[port];
}
return null;
}
public static void OpenAll(string[] ports)
{
foreach (string port in ports)
{
Init(port);
}
}
public static bool Init(string port)
{
if (SerialMap.ContainsKey(port))
{
return true;
}
LogName = "[OKLE_" + port + "]";
if (!ValueBuffer.ContainsKey(port))
ValueBuffer.Add(port, 0);
AcSerialBean sb = new AcSerialBean(port, bautRate, parity, dataBits, stopBits);
try
{
if (sb.openPort())
{
if (SerialMap.ContainsKey(port))
{
SerialMap.Remove(port);
}
SerialMap.Add(port, sb);
return true;
}
else
{
LogUtil.error(LogName + "串口打开失败!");
return false;
}
}
catch (Exception ex)
{
LogUtil.error(LogName + "打开出错:" + ex.ToString());
}
return true;
}
public static bool IsRun(string port)
{
if (GetSerialBean(port) != null)
{
return true;
}
return false;
}
/// <summary>
/// 释放资源
/// </summary>
public static void Release(params string[] ports)
{
if (ports.Length <= 0)
{
ports = (new List<string>(SerialMap.Keys)).ToArray();
}
foreach (string port in ports)
{
try
{
AcSerialBean sb = GetSerialBean(port);
if (sb != null)
{
sb.closePort();
}
//IsRun = false;
SerialMap.Remove(port);
}
catch (Exception ex)
{
LogUtil.error("Release OKLE port [" + port + "] error :" + ex.ToString());
}
}
}
public static bool queryData(string port,out double weight)
{
weight = 0d;
AcSerialBean sb = GetSerialBean(port);
if (sb == null)
{
return false;
}
if (!Monitor.TryEnter(sb))
return false;
try
{
LogName = "[OKLE_" + port + "]";
//12..1.2读取力值(毛重)指令,指令格式:01 03 00 50 00 02 C4 1A
//01 03 00 00 00 02 C4 0B
byte[] sendData = new byte[8];
sendData[0] = 0x01;
sendData[1] = 0x03;
sendData[2] = 0x00;
sendData[3] = 0x00;
sendData[4] = 0x00;
sendData[5] = 0x02;
sendData[6] = 0xC4;
sendData[7] = 0x0B;
//sendData = buildCheckData(sendData, sendData.Length - 2);
string str = AcSerialBean.byteToHexStr(sendData, " ");
byte[] reviceData = new byte[15];
bool isOk = false;
sb.SendCommand(sendData, ref reviceData, 100, out isOk);
//LogUtil.debug(LogName + "发送数据:" + str + ",收到数据 :" + AcSerialBean.byteToHexStr(reviceData, " "));
return getReviceData(reviceData,out weight);
}
catch(Exception e) {
LogUtil.debug(LogName + e.ToString());
return false;
}
finally {
Monitor.Exit(sb);
}
}
private static bool getReviceData(byte[] dataArray, out double value)
{
value = 0d;
try
{
//3D 53 47 2B 30 30 32 30 2E 30 31 6B BE 0D 0A
//=SG+0020.01k�
var tempstr = Encoding.ASCII.GetString(dataArray);
if (tempstr.StartsWith("="))
{
var numstr = tempstr.Substring(3, 8);
if (!double.TryParse(numstr, out value))
{
LogUtil.info(LogName + "转换出错:" + numstr.ToString());
return false;
}
return true;
}
else
{
LogUtil.info(LogName + "转换出错:" + tempstr.ToString());
return false;
}
}
catch (Exception ex)
{
LogUtil.info(LogName + "转换出错:" + ex.ToString());
}
return false;
}
private static byte[] buildCheckData(byte[] sendData, int length)
{
ushort pChecksum = 0;
AcSerialBean.CalculateCRC(sendData, length, out pChecksum);
string checkStr = Convert.ToString(pChecksum, 16);
byte[] checkByte = AcSerialBean.StringToByte(checkStr);
if (checkByte.Length == 1)
{
sendData[length] = checkByte[0];
sendData[length + 1] = 0x00;
}
else
{
sendData[length + 1] = checkByte[0];
sendData[length] = checkByte[1];
}
return sendData;
}
}
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件的差异太大,无法显示。
此文件的差异被折叠, 点击展开。
此文件的差异被折叠, 点击展开。
此文件的差异被折叠, 点击展开。
此文件的差异被折叠, 点击展开。
此文件的差异被折叠, 点击展开。
此文件的差异被折叠, 点击展开。
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!