OHSCE Introductory Tutorial (1) - High Reliability PHP Communication & Control Framework

        "PHP is the best (Internet + Internet of Things) language!" It is said that the release of PHP open source products is a common practice. -2016.10.17 When this article was published, it was OHSCEV0.1.22 version

        Before starting the first tutorial, you always have to sell some feelings. I am an undergraduate majoring in building electrical and intelligence (ie, electrical engineering and automation), and I have always been a serious electrical engineer. In fact, it was originally incompatible with PHP, which is known as the "Web language", but with the guidance of the country's so-called "Internet +", the WEB field has gradually been brought together with all walks of life. From the perspective of many industries, "Internet +" is to a large extent "WEB+", so PHP, the best language, has entered my technology stack. I found that PHP is the most potential industrial control, IoT & intelligent language .

        Open PHP's official website, we can see two white lines of welcome: "PHP is a popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world." - Paraphrase: PHP is a popular and versatile scripting language, especially suitable for Internet-related fields. It's fast, flexible and practical, and the robust PHP can drive everything from your blog to the famous Facebook, Baidu, and more.

       Industrial control industry 4.0, Internet of Things, and industry intelligence will be the next most promising areas of PHP. In line with the principle of not building wheels and making more improvements, I once used the existing PHP communication framework (without serial communication function) to implement the control system once. High error rate, in fact, other people's frameworks are very good WEB frameworks. It may be that the technology stack in the control field is very different from the traditional WEB field. Traditional web engineers have more work content and a powerful browser or APP. Interactive and control engineers are not, so I decided to rewrite a set of code from the ground up (also adding serial communication and shared memory auxiliary hosting functions). This set of codes is specially tailored for the control environment, and is specialized in industrial control industry 4.0, Internet of Things, and industrial intelligence scenarios (of course, it also has the ability to do WEB, after all, ""Internet + ""). In fact, the parent program has been implemented and commercialized several times. We have stripped its core part and then made open source changes and merged the OpenIAC plan to become a high-reliability PHP communication & control framework - OHSCE tailored for control scenarios. It is simple and efficient, and is particularly friendly to the writing style of industrial automation engineers, hardware engineers, IoT engineers, and PHP engineers who pursue efficiency, and it can also make traditional PHP-WEB engineers easy to use.

         Closer to home, we will build a simple serial port server as the content of the first tutorial. A simple serial port server includes uplink network (Ethernet) and fieldbus (here is RS485 communication).

         It is the general trend to use Ethernet as an uplink network. RS485 is currently the most widely used and most cost-effective on-site communication method. Of course, many other communication methods can be transferred with RS232/485, so we take it as an example.

          #Use UDP or TCP?

          UDP is a very good choice, it has no link, is efficient and saves resources, but the disadvantage is the possibility of packet loss, but you can ensure the reliability of your data through the master-slave response, and you can flexibly control Whether to answer or even these features can be part of the logic. However, for the serial port server scenario, TCP is a more suitable choice, because the requirements for making a serial port are very simple, reliable connection to read and write data and forward it to the serial port, and the serial port to write and read data and return it back. We are sure to use TCP

          COM7 of the machine used by the example is the serial port that will be used.

          #If you want to do good things, you must use your tools

          Download the latest version of OHSCE:

          You can download the latest OHSCE from the official website of OHSCE ( http://www.ohsce.org ) or GITHUB ( https://github.com/OpenIBC/Ohsce ). PS. Remember to support me

          Install PHP5.4+ and configure PHP.INI to be available.

          The configuration file to configure OHSCE is located at .../config/

          Enable Curl extension, Shmop extension, Sockets extension

          Create the OhsceComserver.php file

          Load OHSCE

<?php
ini_set('memory_limit',"64M");   //重置php可以使用的内存大小为64M
set_time_limit(0);               //重置运行时长为无限制
ob_implicit_flush(1);
include('loadohsce.php');        //载入Ohsce加载文件              

          #Start to construct the body of the serial server

          First we open the serial port we need to forward

<?php
//......
$comid="COM7";                            //windows下是comx linux下是/dev/ttyX
Ohsce_eng_serial_creat($hscecom,$comid);  //创建一个COM7 9600,n,8,1的待调用串口资源
Ohsce_eng_serial_open($hscecom);          //调用资源并占用该串口 

           PS: The Ohsce_eng_serial_creat function fills in all the relevant parameters you omitted by default, of course you can manually specify them to create various serial port resources.

Ohsce_eng_serial_creat(&$OHSCESerial,$com,$flags="1",$mode=0,$baud=9600,$parity='n',$data=8,$stop=1,$fc='none',$xon='off',$to='off',$octs='off',$odsr='off',$idsr='off',$dtr='on',$rts='on')

          See: Ohsce_eng_serial_creat

         Before creating a TCP server, we need to construct its callback function. The so-called callback function is a function that will be called when a new TCP client arrives and the client sends a new message.

<?php
//...................
function comserveraccept(&$socket,$ip,$port,$zv){ 
	global $hscecom;                                         //调用$hscecom串口资源
	$ohsce_cs_data=Ohsce_socketread($socket,1024);           //读取1024字节数据
	if(($ohsce_cs_data!=null)or($ohsce_cs_data[0]!=false)){
	Ohsce_eng_serial_write($hscecom,$ohsce_cs_data[1],false);//写入串口
    Ohsce_eng_serial_read($hscecom,$data,null,true);         //读取返回数据
	Ohsce_socketwrite($socket,$data);                        //回转所读取的数据
	}
	return true;
}
function comservera(&$socket,$buf,$len,$zv){  
    global $hscecom;
	Ohsce_eng_serial_write($hscecom,$buf,false);
    Ohsce_eng_serial_read($hscecom,$data,null,true);
	Ohsce_socketwrite($socket,$data);
	return true;
}
function comserveralways(&$oibc_clients_zv){
	global $hscecom;
	Ohsce_eng_serial_read($hscecom,$data,null,true);
	if((!is_null($data))and(strlen($data)>0)){
		foreach($oibc_clients_zv['clients'] as $okey => $osclient){
			if($okey=="0"){
				continue;
			}
			Ohsce_socketwrite($osclient,$data);
		}
	}
	return true;
}

          Among them, the comserveralways function is a function that is executed once every cycle of the loop, that is, a resident function. In our serial port server program, he will forward and broadcast the latest received serial port data.

          The comservera(&$socket,$buf,$len,$zv) and comserveraccept(&$socket,$ip,$port,$zv) functions will be fixed to these variables. Where $socket is the pointer of the socket resource of this activity. $buf is the received data. $len is the data length. $ip is the IP address of the newly arrived client. $port is its port. $zv is a fixed structure whose structure is as follows: $oibc_clients_zv=array("clients"=>&$oibc_clients,"ip"=>&$oibc_clients_id_ip,"id"=>&$oibc_clients_id)

        The $oibc_clients array is all current socket resources, and the key value of 0 is the service listener. The $ip array is an ip comparison table. The $id array is the id backup table. Of course, if necessary, you can also print_r to find out.

       Tips: The print_r function is your good helper. In many cases, it is difficult for the documentation to cover all aspects of the QQ group, and it is difficult for me to pay attention to it at any time. At this time, print_r may be more friendly than Du Niang.

        #give it life force

        Well, the callback function and the resident function are all built, let's change it to have the ability to run. The first step is to create a reusable TCP server resource, and the second step is to pass it in to make it run. It's that simple.

<?php
Ohsce_eng_socket_server($ohsceserver,'tcp','7626','127.0.0.1',array('callback'=>'comservera','accept'=>'comserveraccept','fap'=>'comserveralways'),'comserveraccept');          
                                              //创建一个可以复用的SOCKETSERVER资源$ohsceserver,协议为TCP,监听端口为7626,绑定IP127.0.0.1,回调函数为comservera,首次回调函数为comserveraccept,常驻函数为comserveralways.最后一个comserveraccept是为了兼容OHSCEV0.1.22以前的版本。
Ohsce_eng_socket_server_runtcp($ohsceserver); //运行它

       Of course, you can refer to the manual document for more details:  Ohsce_eng_socket_ server   Ohsce_eng_socket_server r_runtcp

       PS: An easter egg, it is best not to use port 7626 in your actual production, because it is too famous. Once we roamed the entire Internet to find friends who opened port 7626. To put it simply, it is easy to recruit blacks, and all recruits are old blacks :)

       #a personal good habit

      No matter how perfect your program is, at the end remember to block and jump to throw an error. This ensures that at least one part of your program will work well when you extend and change other parts of your program.

<?php
//..程序头......
$errmsg='Unknow';
//.............
//..程序身躯....
//.............
goto terror;            //前往并抛出错误
//.............
terror:                 //抛出错误的锚点
exit($errmsg);

       Regarding goto, it can be understood as a JMP instruction, a familiar figure but a slightly different usage. In PHP, GOTO cannot jump from one function to another function, and also cannot jump from one file to another. In fact, this limitation brings an improvement in the readability of your program and a balance between performance & consistency.

       PS. In fact, in many high-level languages, let alone the murderous SETJMP, even GOTO/JMP has been banned. The reason is that a few decades ago, I thought that Mr. "Edsger Wybe Dijkstra" put forward the theory of GOTO being harmful, so it was regarded as an imperial edict by many people, and it was handed down and even cut off in many languages ​​(such as JAVA). This, indeed, greatly reduces the threshold of programming requirements for personnel, but with the development, especially as we enter the era of pan (inter) things (connection) networking (network) network (+), GOTO's kindness and role have become more and more importance. However, Mr. Dijkstra passed away soon after entering the 21st century. The wise PHP design team reintroduced the GOTO keyword to this "best language in the world" in 2009, so from 5.3 we can use efficient, concise, and capable Bottom-up consistency of the GOTO keyword now.

       #niu knife test

      So far, a simple serial port server prototype project has been completed. In fact, it is not only a tutorial case, but also a very practical function. I packaged it, and this prototype was added to the Engine of the V0.1.22_BETA open source version as Alpha. In subsequent versions it will become more and more robust with the version update of OHSCE.

<?php
//.......................................
comserver:
$oibc_cnp_csa=getopt('r:m:p:c:');
Ohsce_eng_serial_creat($hscecom,trim($oibc_cnp_csa['c'])); 
Ohsce_eng_serial_open($hscecom);
function comserveraccept(&$socket,$ip,$port,$zv){ 
	global $hscecom;
	$ohsce_cs_data=Ohsce_socketread($socket,1024);
	if(($ohsce_cs_data!=null)or($ohsce_cs_data[0]!=false)){
	Ohsce_eng_serial_write($hscecom,$ohsce_cs_data[1],false);
    Ohsce_eng_serial_read($hscecom,$data,null,true);
	Ohsce_socketwrite($socket,$data);
	}
	return true;
}
function comservera(&$socket,$buf,$len,$zv){  
    global $hscecom;
	Ohsce_eng_serial_write($hscecom,$buf,false);
    Ohsce_eng_serial_read($hscecom,$data,null,true);
	Ohsce_socketwrite($socket,$data);
	return true;
}
function comserveralways(&$oibc_clients_zv){
	global $hscecom;
	Ohsce_eng_serial_read($hscecom,$data,null,true);
	if((!is_null($data))and(strlen($data)>0)){
		foreach($oibc_clients_zv['clients'] as $okey => $osclient){
			if($okey=="0"){
				continue;
			}
			Ohsce_socketwrite($osclient,$data);
		}
	}
	return true;
}
Ohsce_eng_socket_server($ohsceserver,'tcp',intval(trim($oibc_cnp_csa['p'])),OHSCE_MYIP_SYSTEM,array('callback'=>'comservera','accept'=>'comserveraccept','fap'=>'comserveralways'),'comserveraccept');
Ohsce_eng_socket_server_runtcp($ohsceserver); //开始运行
goto terror;
//.......................................

           Well, let's start it and use TCP to connect to the serial server to read the data of a pressure transmitter using the MODBUS-RTU protocol on the COM7 serial port.

         tcpComClient.php:

<?php
ini_set('memory_limit',"88M");//重置php可以使用的内存大小为64M
set_time_limit(0);
ob_implicit_flush(1);
error_reporting(0);
include('loadohsce.php');
Ohsce_eng_socket_client($ohsceclient,'tcp',7628,'127.0.0.1'); //创建一个TCP客户端资源并连接27.0.0.1:7626
Ohsce_socketsend($ohsceclient['socket'],"\x01\x03\x00\x01\x00\x04\x15\xc9");  //发送数据
//Ohsce_socketsend($ohsceclient['socket'],array('in'=>"01030001000415c9",'bin'=>true));
echo Ohsce_socketread($ohsceclient['socket'],1024)[1]; //收取回复数据
sleep(30);

         running result:

           

         PHP is a robust and versatile scripting language, especially suitable for network-related scenarios. Industrial control, Internet of Things, industry intelligence, OHSCE is your powerful battleship.

          OHSCE official website: http://WWW.OHSCE.ORG

          Technology & Communication: Q Group-374756165 (Suifeng Xinghai@author)

         Manual address: http://www.ohsce.com/index.php/book/ohscelib/

          GITHUB:https://github.com/OpenIBC/Ohsce

          GIT@OSC:https://git.oschina.net/SFXH/Ohsce

          Donate & Support: http://www.ohsce.com/index.php/company/

           

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324104559&siteId=291194637