
//2015.5.27
//开始设计串口协议解析器

unit Protocol
{
	//[i] linkinterface_protocol protocol0;
	link unit protocol0 {}
	
	//[i] var_uint8 OS_EventFlag;
	public uint8 OS_EventFlag;
	//[i] event trig_event;
	
	//[i] var_uint8 OS_time;
	public uint8 OS_time;
	
	->[uint16*?] pro;
	
	int16 index;
	
	bool NeedClear;
	bool ProtocolPause;
	int8 Tick;
	
	//---------------------------------------------------
	//[i] function_void OS_init;
	public void OS_init()
	{
		OS_time = 1;
		OS_EventFlag = 0;
		
		index = 0;
		
		NeedClear = false;
		ProtocolPause = false;
		Tick = 0;
	}
	//---------------------------------------------------
	//[i] function_void OS_run;
	public void OS_run()
	{
		if( ProtocolPause ) {
			return;
		}
		//判断数据是否就绪
		if( !protocol0.IsReady( index ) ){
			return;
		}
		uint8 data = (uint8)(uint16)(uint)protocol0.GetData( index );
		index + 1;
		
		uint16 PData = pro[index];
		uint8 Mask = PData.8(uint8);
		uint8 Value = PData.0(uint8);
		if( Value & Mask != data & Mask  ) {
			//ERROR();
			protocol0.Clear( index );
			index = 0;
		}
		if( (uint)index < pro[0] ) {
			return;
		}
		ProtocolPause = true;
		Tick = 2;
		OS_EventFlag.0(bit) = 1;
	}
	//---------------------------------------------------
	//[i] function_void OS_thread;
	public void OS_thread()
	{
		if( ProtocolPause && Tick > 0 ) {
			Tick - 1;
			if( Tick == 0 ) {
				NeedClear = true;
			}
		}
		if( !NeedClear ) {
			return;
		}
		NeedClear = false;
		protocol0.Clear( index );
		index = 0;
		ProtocolPause = false;
	}
	//---------------------------------------------------
	//[i] function_int32 get_data int32;
	int32 get_data( int32 i )
	{
		NeedClear = true;
		uint32 data = (uint)protocol0.GetData( i - 1 );
		return (int)data;
	}
	//---------------------------------------------------
	//[i] function_void set_protocol protocol;
	void set_protocol( [uint16*?] p )
	{
		pro -> p;
	}
}



