Friday, November 12, 2010

GPIB_PHP_V3

Instrumentation Remote Control through Internet with PHP

João Santos1,2,3, José Mendonça1, João C. Martins1,4

1 Instituto Politécnico de Beja, Escola Superior de Tecnologia e Gestão, Rua Afonso III, 1, 7800-050 Beja, Portugal

2 Centro de Física Nuclear da Universidade de Lisboa, Av. Prof. Gama Pinto, 2, 1649-003 Lisboa, Portugal

3 Laboratório de Instrumentação e Física Experimental de Partículas, Av. Elias Garcia 14 - 1º, 1000-149 Lisboa, Portugal

4 INESC-ID, Rua Alves Redol, 9, 1000-029 Lisboa, Portugal

Email: joao.santos@estig.ipbeja.pt

 



Abstract –This paper describes a set of PHP based tools created to develop applications for instrumentation remote control through web browsers. These tools include a PHP module for GPIB control in a Win32 platform and a set of PHP classes that make easier the creation of GUIs in web browsers for instrument control and data visualization. The Web AJAX technology allows asynchronous data loading making it possible to have in the same browser view different panels that are able to interact and to be updated independently.

 

Keywords virtual measurements; remote laboratory; GPIB; PHP; AJAX.

  1. INTRODUCTION

Computer based instrument control automates the measurement process, making it more reliable and cheaper then when it is done manually by programming individually each instrument through its command panel for every measurement process. Internet allows computer based measurements to be made remotely from almost everywhere with many advantages, either in research, industrial or teaching environment. Instrument operators do not need to be in the laboratory to control their tasks; in hazardous environments this might be crucial. The remote access to a teaching laboratory within an e-learning platform, allows students to use the equipment with less restrictions in time, being able to repeat experiments at their own pace.

The GPIB (General Purpose Interface Bus) is today’s de facto standard interface for computer based control of stand-alone instruments. Though it is being used for over 30 years, its performance, robustness, reliability and simplicity of use have kept it being widely used in the instrumentation industry, and will probably keep it being used for many years to come [1][2].

The GPIB is a digital 8-bit parallel interface that uses 24 lines, 16 of these carrying TTL negative logic signals, and the remaining 8 being used for ground. The 16 signal lines are divided into three groups: 8 data lines, 3 control lines and 5 management lines (fig. 1). The data lines carry messages, either data or specific commands to or from the devices, addresses, and GPIB commands. The control lines use a handshake mechanism to control the asynchronous communication between devices in the bus. The management lines allow the controller to perform all the management operations on the bus [4][5].

Fig. 1. GPIB interface: connections and BUS structure [3].

PHP (PHP: Hypertext Preprocessor) is a programming language originally created for the implementation of dynamic contents in Web pages [6].  It is an object oriented language, with syntax similar to C/C++ and PERL, that allows the development of efficient and robust Web applications. PHP runs on the server side, with efficient CPU and memory use, on many platforms. It is free and Open Source software, with developers all over the world. For these reasons it has become one of the most widely Web scripting languages in use.

PHP is provided with many extensions to interact with other applications, namely databases and Web servers, and allows the development of others to provide more functionalities, if needed. It is perfectly suited to work with the free Open Source packages Apache HTTP server [7] - the most used Web server - and MySQL [8] - the most popular relational database management system for Web applications.

The purpose of the work described in this paper was twofold. First, the creation a PHP extension that, with a HTTP server, makes the functionalities of a GPIB controller available remotely.  Second, the development of a set of PHP classes to ease the creation of applications that use this extension to control instruments. This allows instrumentation remote control with Web browsers, without needing any special client software.

Though there is the effort of the Open Source software communities to provide solutions that span over most of the industrial, governmental or educational domains, the fact is that Win32 platforms keep being extensively used for instrument control and data acquisition. The lifetime of industrial, educational or research equipment exceeds the typical lifetime of general purpose computers and software. When this project began, we were not able to find any solution for GPIB control through PHP for the Win32 platform, though for Linux platforms there is such a solution [9][10]. Similarly, in spite of the PHP widespread use, no set of general use tools to create GUIs for instrument control and data visualization through browsers, similar to the one presented, was found for either of the platforms.

  1. Instrumentation Remote control

The concept of instrumentation remote control through the Web has been around for more than one decade, either in the industry, research and education environments. A standard for instrument control through Ethernet has been established with the VXI-11 protocol [11][12] that can be used with the VISA API [13], either within several commercial off-the-shelf products for instrumentation control, like LabVIEW [14] from National Instruments or VEE [15] from Agilent, or more generic IDEs like Microsoft Visual Studio [16]. Several groups have developed remote educational laboratories for engineering and science teaching [17]–[20], which play an important role in the emerging arena of e-learning. Our approach with this project aims to be as simple as possible in its set-up, using free and Open Source software, within the Win32 platform, and to present very few requisites for the remote users.

A.     Architecture for instrumentation remote control with PHP

Fig. 2. Set-up for instrumentation remote control with PHP.

The proposed architecture (fig. 2) is based on a client/server model. A PC, running an HTTP server with PHP, and controlling the instruments with generic or specific interfaces, acts as the instrumentation server. In the set-up we describe in this paper, this was implemented with a Windows XP platform, with a GPIB board, running the Apache HTTP server, a MySQL database and PHP. Another computer can work remotely as a client and can control the instrument, visualize data on different types of panels and download data gathered from the measurements made by the server. A similar architecture had already been tested using dedicated hardware [21]. As the needs for processing power are mainly on the server side, there is a negligible load on client machines. This makes it adequate for remote access without any significant requisites on the client side, besides possessing a web browser.

B.     The GPIB-PHP driver

A PHP driver was developed as a PHP extension that provides the GPIB functionalities through PHP functions. These functions have syntax similar to the GPIB implementation in C. This driver was developed in C, under Win32, and works according to the structure presented in Figure 3.

 

Fig. 3. Programmatic diagram.

The program structure to control a GPIB device has three blocks. One initialization part, where the interface is initialized and the device is addressed, a program body, where the tasks to deal with the device are defined and executed, and a finalization part where the communication with the controller is closed and computer memory is released.

Some function calls that illustrate the use of the GPIB-PHP driver are presented.

The function ibev opens and initializes a device with a configuration that depends on its six parameters, and returns a device handler. In the following example a digital multimeter is initialized:

 

<? PHP

/* The first value, 0, the boardindex - in the range 0 to (total number of boards - 1)- identifies the GPIB Interface Board the device descriptor is associated with. The second value, 2, is the device primary address – in the range 0 to 30. The device has no secondary address, NO_SAD. The third value, is the device timeout: 10 seconds. The fourth value, specifies that EOI will be asserted with the last data byte, when writing to a device. The last value, specifies “0” as the End-Of-String termination mode to be used when communicating with the device.*/

$dmm = ibev( 0 , 2, NO_SAD, T10s, 1, 0);

if( $dmm < 0 ) echo “The GPIB interface is not available, or the parameters are not correct”;

?>

Two functions of general use are ibwrt and ibrd. The first writes data from a string to the specified device or interface board. The second reads data from a device or interface board into a string. The following code configures a digital multimeter (HP 3478A) to be used as an AC Voltmeter and makes a measurement:

<? PHP

/* The HP 3478A DMM does not comply with IEEE 488.2 specific commands. To configure this device, one needs to use its specific commands. The first value in the function call is the device handle, obtained in the call of ibdev. The second value, “F2”, is the command to the device, which in this case changes the measurement mode to AC VOLT. The last value is the size of the string carrying the command, 2 bytes, in this case. */

ibwrt($dmm , “F2”, 2);

/* The measurement value is stored in the buffer $result. 100 specifies the maximum number of bytes to read.*/

ibrd( $dmm, , 100);

?>

 

A set of thirty four functions covering device level, board level and device/board level are made available to the user in the driver.

C.     GUIs for Instrumentation Control classes

A set of several PHP classes where developed to ease the creation of GUIs in web browsers for instrument control and data visualization. Using the Web AJAX [22] technique makes possible to have in the same browser different panels that are able to interact, and to be updated independently of each other.

AJAX is a group of web techniques that when working together can communicate asynchronously with a web server. The main advantage of using AJAX is the possibility to create more dynamic and interactive web pages, exchanging, big or small, amounts of data with the server to a specific DHTML object, without the need to reload every time it fetches a server response.

The classes developed allow the creation of panels of general use, panels where controls are set, numeric controls, dynamic buttons, two state indicators (LEDs), numeric tanks, numeric slides, analogue displays, and graph controls.

The following PHP script example illustrates the creation of a set of panels with different controls:

 

<div class="main" >

<?php

     $panel2 = new Panel(2,

                 'panel', 'Titulo 2',

                 'teste_meter.php',

                 'auto','800px','100px',

                 '100px',true,true,"#FFF",

                  "1px solid #6699cc");

     $panel3 = new Panel(3,

                 'panel','Teste Grafico',

                 'teste_graph.php','auto',

                 '880px','0px','505px',

                  false);

     $panel4 = new Panel(4,

                 'panel',

                 'Test Tank Control',

                 'teste_tank.php','850px',

                 '500px','0px','0px',

                  false);

     $error = new Panel(6,

                 'panel',

                 'TESTAR GRAPHICO',

                 'gpib.php','auto',

                 'auto','10px',

                 '50px',true);

     $panel4->DisplayPanel();

     $panel2->DisplayPanel();

     $panel3->DisplayPanel();

     $erro->DisplayPanel();

?>

</div>

 

The following examples illustrate the creation of a numeric tank and an analogue display:

<? PHP

$tank = new Controls('','tank1',0,50,-50);

$tank->SetCtrlVal(12.755);

$tank->NumericTank('left',300,100,50,10,

                   10 );

?>

 

<? PHP

$meter = new Controls('',meter,0,50,-50);

$meter->SetCtrlVal(12.755);

$meter->Meter( 'left',300 ,15 );

?>

 

The results of these function calls are displayed on Figure 3. Figure 4 illustrates the use interaction between independent panels, with the definition of the graph control properties through buttons of the other panel.

The PHP, with its straight set of tools to create, manipulate, and query databases, opens a plethora of different applications scenarios for the management of measurements. The security and authentication features of PHP can also be exploited to further enrich the measurements and control applications.

 

tankmet

Fig. 3. Numeric Tank and Analogue Display.

Fig. 4. Graph Control interacting with several buttons and text boxes.

  1. Conclusion

The tools described in this paper allow the creation in a simple and fast way of Web applications for instrumentation control using a widespread programming language like PHP. The innovative character of this approach is to allow instrument control with Web browsers, without needing any special client software, except a ubiquitous browser, and demanding a modest processing power.

The tests performed with an instrumentation server, working for several weeks has shown to be a reliable and robust solution. The GPIB driver was tested with the higher data acquisition rate that our equipment supports, and proved to work as expected.

The extension of the driver capabilities to other boards – this work was carried out with a National Instruments GPIB board – and the development of other classes for control and data analysis is on progress.

REFERENCES

[1]    A. Toth, When Is It Best To Use VXI, PXI, Or GPIB For Your System?, Electonic Design, pp. 22–25, Mar. 15, 2004.

[2]    National Instruments, “The future of GPIB”, NI News, Jan. 29, 2008:

http://www.ni.com/news/archive_files/ninews01292008.htm

[3]    http://www.adlinktech.com/GPIB/intro.html

[4]    IEEE Standard Digital Interface for Programmable Instrumentation, ANSI/IEEE Std 488.1-1987.

[5]    IEEE Standard Codes, Formats, Protocols, and Common Commands for use with IEEE Std 488.1-1987, IEEE Standard Digital Interface for Programmable Instrumentation, IEEE Std 488.2-1992.

[6]    http://www.php.net

[7]    http://httpd.apache.org

[8]    http://www.mysql.com

[9]    M. Billaud, “PHP-GPIB - une extension de PHP pour piloter les instruments GPIB - IEE-488”, 2005:

http://www.labri.fr/perso/billaud/milieu.php?plus=phpgpib#outils

[10] F. Hess, “Linux Gpib package”, Berlin:

http://linux-gpib.sourceforge.net/

[11] J. L. Beckman, A protocol for controlling devices over a network - a new VXI bus draft specification”, in Proc. AUTOTESTCON95, Systems Readiness: Test Technology for the 21st Century, 1995.

[12] VXIbus Consortium, TCP/IP Instrument Protocol Specification - VXI-11,  1995.

[13] VXI plug&play Systems Alliance, VPP-4.3: The VISA Library, October, 2006.

[14] www.ni.com/labview/

[15] www.home.agilent.com

[16] http://msdn.microsoft.com/en-us/vstudio/products/default.aspx

[17] H. Shen et al., “Conducting Laboratory Experiments over the Internet”, IEEE Transactions on Education, vol. 42, no. 3, pp. 180-185, August 1999.

[18] S. K. Esche1 et al., “A Scalable System Architecture for Remote Experimentation”, in Proc. 32nd ASEE/IEEE Frontiers in Education Conference, Boston, 2002.

[19] M. Billaud et al., “Real measures, virtual instruments”, in Proc. 4th IEEE International Caracas Conference on devices, circuits and systems, Caracas, 2002.

[20] F. Gomez-Arribas et al., “eMerge: An European Educational Network for Dissemination of online Laboratory Experiments”, in Proc. International Conference on Engineering Education, Valencia, 2003.

[21] J. Santos et al., “The CRESCERE Muon’s Lifetime Experiment”, Current Developments in Technology-Assisted Education (2006), vol. 2, pp. 1322-1326, FORMATEX, Badajoz, 2006.

[22] http://www.ajax.org

 


Friday, November 24, 2006

Funções GPIB 488.2

Ibask Retorna informação sobre parâmetros configuráveis do software
ibbna Atribuir a um identificador de um dispositivo um nome de acesso á interface
ibclr Limpa dispositivo especifico
ibconfig Alterar parâmetros configuráveis
ibdev Inicializar dispositivo
ibeos Configurar “end-of-string” (EOS) em “termination mode” ou
caracter
ibeot Liga ou desliga a inserção automática da linha GPIB EOI no final de todas as operações I/O
ibln Verifica a presença de dispositivos no BUS
ibloc Modo Local
ibonl Colocar dispositivo ONLINE ou OFFLINE
ibpad Alterar Endereço Primário
ibpct Com a utilização do controlador, passar a comunicação para outro dispositivo
ibrd Ler Dados do dispositivo para a memoria
ibrdf Ler Dados do dispositivo para a um ficheiro
ibrsp Controlar uma “serial poll”
ibsad Alterar ou desligar Endereço Secundário
ibstop Aborta operação I/O assincronizado
ibtmo Alterar ou desligar o período I/O timeout
ibtrg Acciona dispositivo especifico
ibwait Espere por eventos de GPIB
ibwrt Escrever dados da memoria para dispositivo
Ibwrtf Escrever dados de um ficheiro para dispositivo

Monday, November 20, 2006

GPIB (Briefing)

O primeiro GPIB foi criado pela Hewlett-Packard em 1960 com o propósito de conectar instrumentos programáveis da mesma marca (HP-IB). Mas com a entrada de novos instrumentos digitais e equipamentos de teste programáveis, houve a necessidade de criar uma interface standard de grande velocidade que permitisse a comunicação entre equipamentos de diferentes fabricantes.

A primeira standard, ANSI/IEEE Standard 488-1975, será publicada em 1975 pelo “Institute of Electrical and Electronic Engineers” (IEEE), que continha todas as especificações eléctricas, mecânicas e funcionais.

Devido a original IEEE488 não conter nenhuma orientação em relação a sintaxe e formatações convencionais, procurou-se aperfeiçoar todos estes pormenores juntamente com um a necessidade de um aumento de compatibilidade entre instrumentos de teste. Desta investigação resultou o standard IEEE 488.2 que não foi substituir o IEEE 488 renomeando-o para IEEE 488.1.

Em 1990, o IEEE 488.2 inclui o documento “Standard Commands for Programmable Instrumentation” (SCPI), que viria a definir comandos específicos para diferentes classes de instrumentos, garantindo sempre a compatibilidade entre eles e facilitando ao utilizador não obrigação de ter que saber diferentes comandos para cada tipo de instrumentos num sistema SCPI, e até mesmo garantido a possibilidade de substituir instrumentos de marcas diferentes.

Funções com Parâmetros

Para construir uma função que necessita de receber argumentos, o PHP irá recorrer á Macro zend_parse_parameters().

Ex: zend_parse_parameters( zend_num_args() TSRMLS_CC, tipo_variavel, referencia_variavel, referencia_tamanho)


zend_num_args() – retorna um INT com o nº de parâmetros passados para a função

Tipos de Variável:

b -Booleano zend_bool
l -Inteiro long
d -Virgula Flutuante double
s -String char*, int
r -Resource zval*
a -Array zval*
o -Instância de um Objecto zval*
O -Instância de um Objecto de um tipo especifico zval*, zend_class_entry*
z -Zval não especifico zval*
Z -Zval não especifico referenciado zval**

Ex:

Em PHP:

function testPar($value) {
echo " $value ";
}



Em C:

PHP_FUNCTION(testPar)
{
char *value;
int value_len;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
&value, &value_len) == FAILURE) {
RETURN_NULL();
}
PHPWRITE(value, value_len);
}


Parâmetros Opcionais:

| -Valor Opcional
! -Se a variável logo a seguir for do tipo NULL, o PHP irá atribuirlhe o valor interno IS_NULL zval.
/ -Criação de nova variável is_ref==0 e refcount==1.

Tuesday, November 07, 2006

Retornar Valores com Macros e Variaveis

Para cada vez que um a função tiver que retornar valores o PHP terá que utilizar a macros correspondentes para cada tipo de dados.

Macro ZVAL
ZVAL_NULL(return_value)-> RETVAL_NULL()
ZVAL_BOOL(return_value, bval)-> RETVAL_BOOL(bval)
ZVAL_TRUE(return_value)-> RETVAL_TRUE
ZVAL_FALSE(return_value)-> RETVAL_FALSE
ZVAL_LONG(return_value, lval)-> RETVAL_LONG(lval)
ZVAL_DOUBLE(return_value, dval)-> RETVAL_DOUBLE(dval)
ZVAL_STRING(return_value, str, dup)-> RETVAL_STRING(str, dup)
ZVAL_STRINGL(return_value, str, len, dup)-> RETVAL_STRINGL(str,len,dup)

Ex:

PHP:

 $var = 'value'; 


C:

{
zval *var;

MAKE_STD_ZVAL(var);//alocar memoria para variavel
ZVAL_LONG(var, 45);//tipo long
RETVAL_LONG(var);//retornar valor

}

Funções Internas Zend

Estas funções, iniciadas por "zif_", têm como finalidade possibilitar a utilização de nomes de funções do lado do utilizador que possam vir a entrar em conflito com a linguagem C em que se está programar, mas nem sempre esta solução é possivel.
Por exemplo a função "fopen" em PHP não poderia ser implementada directamente, porque iria entrar em conflito com a livraria stdio em C.
A solução passará pela utilização de PHP_NAMED_FUNCTION() para atribuir um nome interno á função que queremos utilizar.

Ex:

PHP_NAMED_FE(check_open_file, fopen, NULL);

Existe também a possibilidade de poder referenciar uma função por mais do que 1 nome, para isso poderemos utilizar o PHP_NAMED_FE().

Ex:

PHP_FE(ex_func, NULL)
PHP_NAMED_FE(func, zif_exp_func, NULL)

Ou mais directamente utilizando as funções PHP_FNAME() e PHP_FALIAS()

Ex:

PHP_NAMED_FE(func, PHP_FNAME (exp_func) , NULL)
PHP_ALIAS(func, exp_func, NULL)

Monday, November 06, 2006

PHP_INFO()

Depois de copiar a dll para a pasta das extensões do PHP o php_info() irá mostrar a tabela com a informação da dll:



Criada pela função PHP_MINFO_FUNCTION :


PHP_MINFO_FUNCTION(gpib){
php_info_print_table_start();
php_info_print_table_header(2, "GPIB Functions", "enabled");
php_info_print_table_row(2, "Gpib Version","0.1");
php_info_print_table_row(2, "Gpib Date","26/10/2006");
php_info_print_table_row(2, "Gpib Author","José Mendonça");
php_info_print_table_end();
/* Remove comments if you have entries
in php.ini DISPLAY_INI_ENTRIES(); */
}