lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Nov 25, 2010 at 4:39 AM, Axel Kittenberger <axkibe@gmail.com> wrote:
> (lua)posix.fileno() does what you want.
>

posix.fileno(io object) works to get the fileno. Attached scripts works.

Any ideas why I can't get the serial port to work bidirectionally? I
need to have it open on two different handles to make it work.

This is based on verse, and xmpp client lib.
http://matthewwild.co.uk/projects/verse/verse_doc.xml

I am trying to get remote access to a serial port over a xmpp session.
The device on the serial port talks binary, so I am converting the
conversation to hex.

require "posix"

os.execute("stty -F /dev/ttyUSB0 19200 cread min 0 time 9")

ttyin = assert(io.open("/dev/ttyUSB0", "r"));
ttyin:setvbuf("no");
ttyout = assert(io.open("/dev/ttyUSB0", "w"));
ttyout:setvbuf("no");

print("ttyin ", posix.fileno(ttyin));
print("ttyout ", posix.fileno(ttyout));


local serial = {
	getfd = function () return posix.fileno(ttyin); end;
	dirty = function (self) return false; end;
	settimeout = function () end;
	send = function (_, data, i, j)
		ttyout:write(data:byte(i,j))
		-- Send data:sub(i,j) to serial, return bytes written
		return #data, 0; end;
	close = function () end;
	receive = function (_, patt)
		return ttyin:read(1000);
	end
};

local function on_incoming(serial, data)
	if ((data ~= nil) and (data:len() ~= 0)) then
		local s = "";
		for i = 1, #data do
			s = s..string.format("%02x", data:byte(i,i))
		end	
		io.write(s, "\n");
		c:send(verse.message({type = "chat", to = "jonsmirl@digispeaker.com"}, s));
	end
end

-- Registers the fake socket with net.server, and returns the
server.lua conn wrapper object
local serial_conn = require "net.server".wrapclient(serial, "serial", 0, {
	onincoming = on_incoming }, "*a");

-- Change these:
local jid, password = "jonsmirl_house@digispeaker.com", "password";

-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
-- os.execute("squish --minify-level=none --use-http ../verse");

require "verse" -- Verse main library
require "verse.client" -- XMPP client library

c = verse.new();
c:add_plugin("version");
c:add_plugin("legacy");

-- This one prints all received data
--c:hook("incoming-raw", print, 1000);

-- This one prints all received data
c:hook("message", function (data)
	local s = "";
	local body = data:get_child("body"):get_text();
	for i = 1, #body, 2 do
		s = s..string.char(tonumber(body:sub(i,i + 1), 16));
	end	
	--serial_conn:write(s);
	ttyout:write(s);ttyout:flush()
end, 1000);

-- Now, actually start the connection:
c:connect_client(jid, password);

-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
	c.version:set{ name = "verse example client" };
	c:send(verse.presence():tag("priority"):text("0"));
end);

verse.loop()




-- 
Jon Smirl
jonsmirl@gmail.com