Version française
Home     About     Download     Resources     Contact us    
Browse thread
Lwt try_bind question...
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Tim Hanson <sideskate@g...>
Subject: Lwt try_bind question...
Hi All,
I've been trying to use Lwt in my application (robot control).
(Background: there are 3 executables, all running simultaneously,
which communicate via sockets.  The ocaml program coordinates/controls
the video program and servo control program. )

In the file below, @ line 43 using the try_bind function I try to read
from the socket, and if it fails, wait 3 seconds before trying again.
But, I can't figure out how to make it compile.  I'm sorry if this is
fairly obvious, but the web has yet to turn up anything to fix it.
(perhaps it will in the future now :-)

I compile with the following line:
ocamlfind ocamlc -c -package lwt,lwt.unix,lwt.syntax -syntax camlp4o relay.ml

any advice will be much appreciated!

Tim
--------
open Lwt

let new_socket () = Lwt_unix.socket Unix.PF_INET Unix.SOCK_DGRAM 0
let local_addr num = Unix.ADDR_INET (Unix.inet_addr_any, num)

let _ =
	Lwt_unix.run (
		(* init a 'server' port for video prog to connect to *)
		let video_socket = new_socket () in
		Lwt_unix.setsockopt video_socket Unix.SO_REUSEADDR true;
		Lwt_unix.bind video_socket (local_addr 4594);
		Lwt_unix.listen video_socket 1;
		(* init a 'client' address to connect to the servocontroller *)
		let banger_socket = new_socket () in
		Lwt_unix.setsockopt banger_socket Unix.SO_REUSEADDR true;
		ignore_result(Lwt_unix.connect banger_socket (local_addr 4593));
		
		let printo s = ignore_result(Lwt_io.printl s) in
		
		(* Wait for a connection from video tracker*)
		ignore_result(Lwt_unix.accept video_socket >>= (fun (inp, _) ->
			printo "video socket connected!\n%!";
			let buffer = String.create 512 in
			(* set up a calibration sequence .. just to test *)
			let rec calib () =
				let msg = "L\n" in
				ignore_result(Lwt_unix.write inp msg 0 (String.length msg)) ;
				Lwt_unix.read inp buffer 0 512 >>= (fun len ->
					let ss = String.sub buffer 0 len in
					printo("got video data:"^ss);
					Lwt_unix.sleep 3.0 >>= calib
				)
			in
			calib ()
		));
		(* simultaneously, read from the servocontroller *)
		let buffer = String.create 512 in
		let rec read_banger len =
			if len > 0 then (
				let ss = String.sub buffer 0 len in
				printo("got servo data:"^ss)
			);
			try_bind
				(fun () -> (Lwt_unix.read banger_socket buffer 0 512))
				(fun n -> read_banger n )
				(fun _ -> (Lwt_unix.sleep 3.0) >>= read_banger 0 )
		in
		read_banger 0
	)