Python and EPICS CA EPICS Seminar In RRCAT, Indore, India 2009.1.30 Noboru Yamamoto.

Similar presentations


Presentation on theme: "Python and EPICS CA EPICS Seminar In RRCAT, Indore, India 2009.1.30 Noboru Yamamoto."— Presentation transcript:

1 Python and EPICS CA EPICS Seminar In RRCAT, Indore, India 2009.1.30 Noboru Yamamoto

2 I. CA Clients

3 CA Clients CA Cliens:  Applications usnig EPICS CA client library  EPICS tools edm/medm: GUI builder Channel Archiver : data logging/archiving Sequencer : fast & complex control logic Alarm handler Just needs configuration of tools.

4 Why Python (or other script languages) If your requirement exceed ability of EPICS tools.  Think again if it cannot be implemented using standard CA clients  Write you own application C/C++ Script Languages:(SAD, Tcl/Tk, Perl, Python, Java, …)  Allow Rapid Application Development

5 Script languages Tcl/Tk, Perl, Python, (Java), SAD etc  Quick development  May be slower than other method(C/C++ or Sequencer), but fast enough for most applications.  Has rich set of libraries, including GUI, Network, RDB etc.  Mostly used for host side applicaions.

6 Python One of Object Oriented scripting languages Widely used: RedHatLinux installer/Google applications / mailman Suppor multipl platform (Linux, Win, mac, Java) Rich set of standard library  GUI(Tkinter, wxPython)  Numerical/Matirix(NumPy),  chart(Gnuplot, matplot)

7 Python and EPICS Python module for EPICS Channel Access library  KEK version  FNAL version Support most of functionality in CA library Channel object in python is introduced. In Jython, you can call jca/caj library directly. EPICS-CA interface is available in other script languages, too.  CAP5 for Perl.

8 Python-EPICS CA (KEK) Two modules : ca.py and cas.py based on common C-module. Simple functions in ca.py  ca.Get  ca.Put  ca.Put_Array  ca.Info  ca.Monitor Channel object

9 Channel Object Import ca ch=ca.channel(“fred”) Properties  Val, ts, severity, status,... Channel object methods:  Put, get, monitor, auto_update  Flush, pend_io, get_info,....

10 Sample program import ca access={0:"no",1:""} chan=ca.channel("fred") chan.wait_conn() # wait ca connection to complete # print out channel information print " PV name: %s"%chan.name print " Data type: %s"%chan.field_type print " Element count: %d"%chan.element_count print " Host: %s"%chan.hostname print " State: %s"%chan.state() print " Connected : %s"% chan.isConnected() print " Access: %sread, %swrite"%(access[chan.raccess], access[chan.waccess])

11 Sample program(cont'd) def callback(valstat): chan.update_val(valstat) val, sevr, status,ts=valstat print "" if (status): print "%-30s %s"%(chan.name, status) else: print " Value: %g"%val print " Severity: %s"%sevr print " Timestamp: %s"%ca.TS2Ascii(ts) chan.monitor(callback) # register callback to monitor chan.flush() # flush out CA library buffer ca.pend_event(0) # wait for monitor event forever

12 Sample program with CAP5/perl use lib '/opt/epics/R314/modules/soft/cap5-0.3/lib/perl'; use CA; my $chan = CA->new('fred'); CA->pend_io(1); my @access = ('no ', ''); printf " PV name: %s\n", $chan->name; printf " Data type: %s\n", $chan->field_type; printf " Element count: %d\n", $chan->element_count; printf " Host: %s\n", $chan->host_name; printf " State: %s\n", $chan->state; printf " Connected : %s\n", $chan->is_connected; printf " Access: %sread, %swrite\n", $access[$chan->read_access], $access[$chan->write_access]; die "PV not found!" unless ($chan->is_connected);

13 Sample program with CAP5/perl $chan->get; CA->pend_io(1); printf " Value: %s\n", $chan->value; $chan->create_subscription('v', \&callback, 'DBR_TIME_DOUBLE'); CA->pend_event(10); sub callback { my ($chan, $status, $data) = @_; if ($status) { printf "%-30s %s\n", $chan->name, $status; } else { printf " Value: %g\n", $data->{value}; printf " Severity: %s\n", $data->{severity}; printf " Timestamp: %d.%09d\n", $data->{stamp}, $data->{stamp_fraction}; }

14 II. Python プログラム言語 (Python2.5/2.6 準拠 )

15 Hello World Program 文字列 “Hello World!” を画面に表示する Python program print “Hello World!” 別バージョン def main(): print “Hello World!” if __name__ == “__main__”: main()

16 Python program の実行例(1) [noboru-mbook:~] % python Python 2.6 (r26:66714, Dec 3 2008, 22:16:48) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World!" Hello World! >>>^ D [noboru-mbook:~] % python コマンドでプログラムを起動する。 python のプロンプト ”>>>” で直接 Python のプログラム文を入力すると直ちに実行さ れる(インタプリタ) ^ D(Control+D) で Python インタプリタを終了。

17 Python program の実行例( 2 ) [noboru-mbook] % cat HelloWorld.py #!/usr/bin/env python def main(): print "Hello", print " World!" if __name__ == "__main__": main() [noboru-mbook]% python HelloWorld.py Hello World! [noboru-mbook] % chmod +x HelloWorld.py [noboru-mbook] %./HelloWorld.py Hello World! file”HelloWorld.py” に Python プログラムを作成 ファイルの python プログラムを python コマンドで直接実行 Python プログラムをコマンドとして実行することも可能。

18 Python プログラムの作成 作成ツール  emacs, xedit などのテキストエディタ emacs では python-mode が利用可能 その他のエディタでもサポートモジュールがある場 合がある。  idle python で作成された開発ツール、 Linux,Windows, MacOSX 等で動作  eclipse+PyDev Java の開発環境に Python 向けモジュールを追加。

19 emacs/Python-mode .py のファイルを自動判定して Python- mode になる。  Tab で固定長のインデントを挿入  予約語、文字列等を色で区別。  ^ C ^ C で python 処理系を起動してファ イルを実行  o Python mode であることを表示

20 Python プログラムのファイル名 python プログラムのファイル名は、  拡張子 ”.py” を使う。 python を実行すると、 ”.pyc”, “.pyo” といったファ イルが生成されることがある。これらは python 処 理系が使用するので、そのままにしておいてくだ さい。  ファイル名に空白や記号 (“+”,”-” など)を入れると後 で module として使う際に障害となるので、アルファ ベットと数字、 ”_” 等の組み合わせにしておくのが安 全です。

21

22 Python のデータ型 整数 : 1, 浮動小数点, 複素数 : 3.14, 1+0.2j 文字型 : “abc”, u” あいう ” リスト (list) : [1,2,3] タプル (tuple) : (1,2,3) 辞書 (dict):key と値のペアの集まり :  dict(a=1,b=2,c=3), {“a”:1,”b”:2,”c”:3} 関数オブジェクト : def foo: オブジェクト : class obj:

23 Python の文 式 : 1+2 代入文 : x=y*z print 文 : print “Hello World” import 文: import os def 文:関数定義  return 文: return val  yield 文 if 文 : if (cond): ~ elif (cond) :~ else: ~ while 文 : while 1 :~ for 文 : for i in range(100):~  break 文、 continue 文 try 文 : try: ~ except : ~ else: ~ finally:  raise 文

24 Python の演算子 単項演算子 : +, -, ~ 二項演算子: +,-,*,/, %( 剰余 ),//( 切り捨て ), **( 羃乗 ) 比較:, ==, >=,, !=, is, in, is not, not in 論理演算子: and, or, not ビット演算: &, |, ~, ^, >

25 スライス リストやタプル、文字列といったシークエン ス型のオブジェクトの要素を取り出す  object[n] 0 から数えて n の要素  object[-n] シークエンスの後ろから n 番目の要素  object[i:j] 0 から数えて i から j 未満の要素. “ 通常 ”, (j-i) 個の要素  object[i:j:k] k 毎の i から j までの要素

26 EPICS と Python

27 Python と EPICS Ca ライブラリを利用するための ca モジュー ルおよび cas モジュールが用意されている。 ca モジュールと cas モジュールはどちらも C で書かれた _ca モジュールを利用している。 ここでは基本的な ca モジュールを使って説明 を行う。

28 ca module ca module では、  Get/Put/Monitor/Put_Array/Info などの簡易利用関 数  channel クラス が用意されている。  channel クラスを利用することで、 CA ライブラ リのほとんどの機能を利用可能。また、効率的 な利用が可能。

29 実践的(?)例題 与えられたレコードリストの各レコードにつ いて、 HOPR フィールドの値を 100.0 、 LOPR フィールドの値を 0.0 に設定する。

30 プログラム例 import ca def SetHOPR(name,hopr=100.0): ca.Put(name+”.HOPR”, hopr) return ca.Get(name+”.HOPR”) def SetLOPR(name,lopr=0.0): ca.Put(name+”.LOPR”,lopr) return ca.Get(name+”.LOPR”) def main(): channels=(“fred”,”jane”,”freddy”,”janet”) for ch in channels: hopr=SetHOPR(ch) lopr=SetLOPR(ch) print “new operating range for %s is (%d,%d)”%(ch, hopr, lopr) if __name__ == “__main__”: main()

31 Import 文 module を import( プログラム中にロード ) して利用可 能とする。 標準的なライブラリはモジュールの形で提供され る。  sys, math, os, string, …  ca EPICS channel access module モジュール内のオブジェクト(クラス、関数等) はモジュールの名前とあわせて指定する。  例 ; ca.Get, ca.Put

32 from ~ import ~ Module 内のオブジェクトを実行中の名前空 間に直接ロードする。  例: from ca import Get, Put v=Get(“fred”); Put(“jane”,v+1)

33 関数定義 def SetHOPR(name,hopr=100.0): ca.Put(name+”.HOPR”, hopr) return ca.Get(name+”.HOPR”) 関数 ”SetHOPR” を定義 (def) する。 この関数は二つの引数 (name,hopr) を持つ。 引数 hopr は呼び出し時に省略可能で既定値 (100.0) を持 つ。 引数のレコード名にフィールド名 (.HOPR) を付け加え (+) チャンネル名とする。 ca.Put で HOPR フィールドを設定 ca.Get が返す値をこの関数の戻り値として返す (return)

34 繰り返し (for 文 ) channels=(“fred”,”jane”,”freddy”,”janet”) for ch in channels: hopr=SetHOPR(ch).... Python の for 文は (for ~ in ~:) の形をとる。 ループ変数とその変数がとる値を指定するシークエ ンス型のデータ ( リスト、タプル、文字列)あるいは イテレータ型のデータを与える。

35 for 文 ( 続き ) C/C++ の for(i=0;i<100;i++){ … } は Python では for i in xrange(100):..... となる。 xrange(100) は (0..99) を値の範囲とする xrange オブジェクト

36 If __name__ == “__main__””: python が今実行中のプログラムの名前空間が __name__ グローバル変数に設定されている。 Python プログラムが(モジュールとしてロードさ れているのではなく)主プグラムとして実行され ているときには __name__ の値は ”__main__” となる 。 この常套句をつかうことで同一ファイル (Python プ ログラム ) をライブラリ( module) としても、単独の アプリケーションとしても使い分けることが可能 になる。

37 プログラムの改造例 import ca Def SetChVal(chname,val): ca.Put(chname, val) return ca.Get(chname) def SetHOPR(name,hopr=100.0): return SetChValt(name+”.HOPR”, hopr) def SetLOPR(name,lopr=0.0): return SetChValt(name+”.LOPR”, hopr) def main(): channels=(“fred”,”jane”,”freddy”,”janet”) for ch in channels: hopr=SetHOPR(ch) lopr=SetLOPR(ch) print “new operating range for %s is (%d,%d)”%(ch, hopr, lopr) if __name__ == “__main__”: main()

38 これから Python について 学ぶべきこと モジュールの作成 オブジェクト指向プログラム  class エベント駆動プログラム  thread  thread.lock Graphical User Interface の作成  Tkinter  WxPython module の探し方  教科書/参考書  Web/Internet (www.python.jp, www.python.org)www.python.jp


Download ppt "Python and EPICS CA EPICS Seminar In RRCAT, Indore, India 2009.1.30 Noboru Yamamoto."

Similar presentations


Ads by Google