Homer
Published © MIT

Make a Serial TCP Converter with PHPoC

Turn your serial equipment into Internet-connected devices, with a converter that transform data between Serial and TCP.

BeginnerFull instructions provided1 hour824
Make a Serial TCP Converter with PHPoC

Things used in this project

Hardware components

PHPoC Black
PHPoC Black
×1
Smart RS232 Board
PHPoC Smart RS232 Board
×1

Story

Read more

Code

task_serial.php

PHP
Main program that should be run in a loop. Don't forget to insert this line into init.php: system("php task_serial.php");
<?php
if(_SERVER("REQUEST_METHOD"))
	exit; // avoid php execution via http request
include "/lib/sd_spc.php";
include "/lib/sn_tcp_ac.php";

define("SPC_ID",	2);
define("TCP_ID",	0);
define("TCP_PORT",	1470);

function spc_uart_read($spc_id, &$buf)
{
    $rlen = (int)spc_request_dev($spc_id, "get rxlen");
    if ($rlen)
        $buf = spc_request($spc_id, 6, "$rlen");
    else
        $buf = "";
    return $rlen;
}

function spc_uart_write($spc_id, $buf)
{
    spc_request($spc_id, 7, $buf);
}

$uart_buf = "";
$tcp_buf = "";

// Initialize serial parameters
spc_reset();
spc_sync_baud(115200);
spc_request_dev(SPC_ID, "set uart 115200N81");

// set PHPoC as TCP Server
tcp_server(TCP_ID, TCP_PORT);

while(1)
{
	if(tcp_state(TCP_ID) == TCP_CONNECTED)
	{
		// read incoming serial data and forward to tcp
		$rlen = spc_uart_read(SPC_ID, $uart_buf);
		if ($rlen)
		{
			tcp_write(TCP_ID, $uart_buf);
		}

		// read incoming tcp data and forward to serial
		$rlen = tcp_read(TCP_ID, $tcp_buf); 
		if ($rlen)
		{
			spc_uart_write(SPC_ID, $tcp_buf);
		}
		
	}		
}
?>

Credits

Homer
17 projects • 46 followers
Contact

Comments

Please log in or sign up to comment.