How do i use socket.select? - lua

I need some help using socket "select" function.
My server code is like this:
while true do
for _,server in pairs(servers) do
local client = server:accept()
client:settimeout(5)
local line, err = client:receive()
if not err then
client:send(line .. "_SERVER_SIDE\n")
else
client:Send("___ERRORPC"..err)
end
client:close()
end
end
But now i want to use the select function instead of make a forever loop like this.
Reading this: http://w3.impa.br/~diego/software/luasocket/socket.html
I know that i can use something simmilar than:
socket.select(servers, nil, 5)
But i donĀ“t know how i can use this on the code above. Can anyone help me?
I will have to use this inside a while true statement?
The reading operation (first parameter) means that i can only make an accept/receive]? And the seconds parameter means that i can only make a send?

As per the documentation, select receives one or two arrays of sockets and returns an array of sockets that can safely be read from without blocking and an array of sockets that can be safely written to without blocking and an array of sockets that can safely be written without blocking. An important point is that the first array is for both server sockets that want you want to call accept on and for client sockets that you want to call receive on.
The seconds parameter is just a timeout for the select. It doesn't have to do with how many operations you can make.
The basic thing you are going to have to change in your code is that when a receive call fails with a timeout, instead or giving an error you should add that socket to the array of sockets that you pass to select. This way you can have select tell you when that socket becomes active again.

From the documentation for select: "calling select with a server socket in the receive parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever." This means that you'd need to use settimeout before your accept call, but assuming you have a list of opened connections you can work with in servers table, you can use select in the following way:
local canread = socket.select(servers, nil, 1)
for _,client in ipairs(canread) do
local line, err = client:receive()
if not err then
client:send(line .. "_SERVER_SIDE\n")
else
client:send("___ERRORPC"..err)
end
end
socket.select will block for up to 1 second, but will return sooner if there is a socket from the list you provided that can be read from. You can block indefinitely if you use socket.select(servers, nil, 0); blocking for some short time is useful if you need to do some other work while waiting for the input.
Updated to use ipairs instead of pairs as the returns table is keyed both on numbers as well as on sockets themselves, so if one socket can be read from, the returned array looks like {[1] = sock, [sock] = 1}.

single demo
local server = socket.bind("*",7777)
local client_tab = {}
while true do
-- socket.select first param is a table of connected socket,
-- you want a connected socket,you need to call accept()
-- if you do not want to block,you should call settimeout(seconds)
local recvt = socket.select(client_tab, nil, 1)
server:settimeout(1)
local client = server:accept()
if client then
client_tab[#client_tab+1] = client
end
if #recvt > 0 then
-- read clients in recvt
end
end

Related

Bailing people out of prison in roblox using Remote Events doesn't seem to work properly

Here's the deal. When you get arrested in my game, you get sent to jail. To get out you must be bailed out.
The client sends a request to the server to bail them. Every other part seems to work except this part I believe, however it could be the client side script. Is there anything incorrect about this script? I have checked it for any errors that are obvious to me.
local replicatedStorage = game:GetService('ReplicatedStorage')
local createSystemMessage = replicatedStorage:WaitForChild('CreateSystemMessage')
game.ReplicatedStorage.Bail.OnServerEvent:Connect(function(Player,PlayerToBail)
Player = game.Players:FindFirstChild(Player)
local tab = nil
for i,v in pairs(_G.GlobalData) do
if v.Name == Player.Name then
tab = v
end
end
if PlayerToBail.Team == game.Teams:FindFirstChild("Criminal") then
local Bounty = PlayerToBail.leaderstats.Bounty.Value * 2
if tab.Bank <= Bounty then
tab.Bank -= Bounty
PlayerToBail.leaderstats.Bounty.Value = 0
PlayerToBail.Prisoner.Value = false
PlayerToBail.Team = game.Teams:FindFirstChild("Civilian")
createSystemMessage:FireAllClients((Player.Name .. ' has Bailed ' .. PlayerToBail.Name), Color3.fromRGB(0, 250, 0))
end
end
end)
And the local script which works:
script.Parent.AcceptButton.MouseButton1Click:Connect(function()
local PlayerName = script.Parent.TargetName.Text
game.ReplicatedStorage.Bail:FireServer(PlayerName)
print ("Bail Requested")
end)
I believe the problem occurs with the argument you're passing to the remote event.
In your client script you pass PlayerName as an argument. I'm assuming this is a string of the player's name:
game.ReplicatedStorage.Bail:FireServer(PlayerName)
PlayerName will actually be sent to the parameter "PlayerToBail", which I'm assuming is supposed to be a player object. Keep in mind that Roblox's RemoteEvents automatically pass in the player who fired the remote event as the first argument. So the "Player" parameter of the function connected to your remote event is the actual player object that has the local script that fired the remote event.
Instead, I would fire the remote event like this:
game.ReplicatedStorage.Bail:FireServer()
Since the player you want to bail is automatically passed as an argument, you don't need to add any additional arguments to FireServer. In addition, you would get rid of the "PlayerToBail" parameter in your server script.
Also note, it is unnecessary to have this line of code in your server script:
Player = game.Players:FindFirstChild(Player)
Player is already referring to an object in game.Players. In addition, Player is an object, not a string. So this would not work. You can simply use Player as is for your purposes.
More info on Remote Events: https://developer.roblox.com/en-us/articles/Remote-Functions-and-Events
Please feel free to follow up if you still have issues.
When firing the server it automatically gives a parameter which is the player who sent it. So, you don't have to have the playerName part because after the player parameter is already there and you can get the name from that.

Is there a way to get the last chat massage in shout or say?

I want to search the last message for a few strings and then echo the message back with those strings replaced with other strings.
I searched multiple documentations but didn't find a way to get the last message.
This is the first forum I ask as I already have an account so have no real starting point to give you.
Thanks in advance!
There is no way in the WoW API to get the last chat message of a specific channel. You will have to handle the CHAT_MSG_CHANNEL event (see Event Handling) to read all messages, and store the newest one. Specifically for the say or yell (shout) channels there are the CHAT_MSG_SAY and CHAT_MSG_YELL events respectively.
To do this your addon needs to own a Frame, these frames can register event handlers and you will have to store the last message you receive from that handler in a local variable in your script (let's call it last_message). Then when your other piece of code executes you can read the last_message variable:
local frame = CreateFrame("FRAME", "FooAddonFrame");
local last_message = nil;
frame:RegisterEvent("CHAT_MSG_CHANNEL");
local function eventHandler(self, event, ...)
-- Look up the arguments that are given to your specific event
-- and assign them to variables in order by retrieving them from
-- the `...` variable arguments
local msg, author, language, channel = ...
print("Hello World! Hello " .. event);
last_message = msg
end
frame:SetScript("OnEvent", eventHandler);

With Lua/NodeMCU, how can I wait until >1 mqtt publish calls have been made before running a block of code?

My application involves a battery-powered ESP8266 running NodeMCU for the purpose of updating sensor values periodically over MQTT.
To save battery life, I want to call dsleep() as soon as I'm done with my work. That work might involve more than 1 call to mqqt.Client.publish(). This brings us to the problem I'm facing.
I'm a Lua newbie, but as I understand, the right way to run some code after publish() has finished is to give it a PUBACK callback:
m = mqtt.Client(...)
m.publish("/my/topic", "some message", 1, 0, callback_func)
And in a simple case like above, that works great - even though the actual sending of the MQTT message is async with regard to the publish() call (see a good discussion of this here), callback_func() in the above example will only be called when publish() is done.
But when I have more than 1 call to publish() and want my callback to a) be called after they're all complete, and b) only be called once, I'm stuck.
The naive approach to this would be to put the callback (which is optional) only on the Nth publish() call:
m = mqtt.Client(...)
m.publish("/my/topic", "some message", 1, 0)
m.publish("/another/topic", "unrelated message", 1, 0, callback_func)
But this will not do what's expected. As documented:
NOTE: When calling publish() more than once, the last callback function defined will be called for ALL publish commands.
So in the above example, callback_func() ends up getting called twice (once for each successful publish().
I could combine the multiple publish() calls into a single call, but that feels like an ugly hack, and would have other adverse implications. If my two messages are conceptually distinct, this approach would push logic to separate them into the subscriber - yuck. And if they needed to go to different topics, this would be even worse. There must be a better way.
I thought perhaps mqqt.Client.close() would wait for my different publish() calls to finish, but it doesn't.
I'm out of ideas, and hoping someone with more Lua and/or NodeMCU+mqqt experience can give me a nudge in the right direction.
Here's my actual code, if it helps:
-- prior to this, we've gotten on the wifi network and acquired an IP
dofile("temp.lua") -- provides get_temp()
m = mqtt.Client("clientid", 120, "8266test", "password")
function mainloop(client)
print("connected - at top of loop")
m:publish("uptime",tmr.time(),1,0, function(client) print("sent uptime") end)
temp, humi = get_temp()
if (temp ~= nil) then
print(string.format("temp: %d", temp))
print(string.format("humi: %d", humi))
m:publish("temp",temp,1,0)
m:publish("humi",humi,1,0, function(client) -- note: this callback will be used for all publish() calls
rtctime.dsleep(SLEEP_USEC)
end)
end
end
m:on("connect", mainloop)
m:on("offline", function(client) is_connected = false print ("offline") end)
m:connect(MQQT_SVR, 1883, 0, mainloop,
function(client, reason) print("failed reason: "..reason) end)
Option 1:
publish all data at once, then go to sleep.
Option 2:
split your callback into two parts. the first part checks if you are done, the second part goes to sleep if you are done.
Of course you can solve this differently, count how many are left, count how many you have sent, send and remove items from a list until the list is empty,...
Of course there are more options but these are simple and sufficient.
Edit: example as requested
local totalItemCount = 5
function publishCallback()
itemsPublished = (itemsPublished or 0) + 1
print("item published")
if itemsPublished == totalItemCount then
print("I'm done, good night!")
end
end
for i = 1, totalItemCount do
publishCallback()
end
item published
item published
item published
item published
item published
I'm done, good night!

Lua making game loop and other functions

So like i have mainloop and many other functions but i cant call them because of there is infinitive loop how can i make them so i can call the functions.
local socket = require("socket")
local function sleep(sec)
socket.select(nil, nil, sec)
end
coroutine.wrap(function()
while true do
sleep(1)
end
end)()
print("bob") -- like here
like in code it doesn't print bob because there is loop is way avoid that i tried using corountines but they didnt work
Normally I would suggest using non-blocking commands, but I'm not certain what socket.select is doing. It appears you are misusing it as a blocking timer.

NodeMCU timeout when using while loop

I have a Lua script that sends an email to myself via SMTP. Everything works fine when uploading to the NodeMCU and saying dofile("sendemail.lua").
-- sendmail.lua
-- The email and password from the account you want to send emails from
MY_EMAIL = "REDACTED"
EMAIL_PASSWORD = "REDACTED"
-- The SMTP server and port of your email provider.
-- If you don't know it google [my email provider] SMTP settings
SMTP_SERVER = "isp.smtp.server"
SMTP_PORT = 25
-- The account you want to send email to
mail_to = "REDACTED"
-- Your access point's SSID and password
SSID = "REDACTED"
SSID_PASSWORD = "REDACTED"
-- configure ESP as a station
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,SSID_PASSWORD)
wifi.sta.autoconnect(1)
email_subject = ""
email_body = ""
count = 0
local smtp_socket = nil -- will be used as socket to email server
-- The display() function will be used to print the SMTP server's response
function display(sck,response)
print(response)
end
-- The do_next() function is used to send the SMTP commands to the SMTP server in the required sequence.
-- I was going to use socket callbacks but the code would not run callbacks after the first 3.
function do_next()
if(count == 0)then
count = count+1
IP_ADDRESS = wifi.sta.getip()
smtp_socket:send("HELO "..IP_ADDRESS.."\r\n")
elseif(count==1) then
count = count+1
smtp_socket:send("AUTH LOGIN\r\n")
elseif(count == 2) then
count = count + 1
smtp_socket:send("REDACTED".."\r\n")
elseif(count == 3) then
count = count + 1
smtp_socket:send("REDACTED".."\r\n")
elseif(count==4) then
count = count+1
smtp_socket:send("MAIL FROM:<" .. MY_EMAIL .. ">\r\n")
elseif(count==5) then
count = count+1
smtp_socket:send("RCPT TO:<" .. mail_to ..">\r\n")
elseif(count==6) then
count = count+1
smtp_socket:send("DATA\r\n")
elseif(count==7) then
count = count+1
local message = string.gsub(
"From: \"".. MY_EMAIL .."\"<"..MY_EMAIL..">\r\n" ..
"To: \"".. mail_to .. "\"<".. mail_to..">\r\n"..
"Subject: ".. email_subject .. "\r\n\r\n" ..
email_body,"\r\n.\r\n","")
smtp_socket:send(message.."\r\n.\r\n")
elseif(count==8) then
count = count+1
tmr.stop(0)
smtp_socket:send("QUIT\r\n")
print("msg sent")
else
smtp_socket:close()
end
print(count)
end
-- The connectted() function is executed when the SMTP socket is connected to the SMTP server.
-- This function will create a timer to call the do_next function which will send the SMTP commands
-- in sequence, one by one, every 5000 seconds.
-- You can change the time to be smaller if that works for you, I used 5000ms just because.
function connected(sck)
tmr.alarm(0,5000,1,do_next)
end
-- #name send_email
-- #description Will initiated a socket connection to the SMTP server and trigger the connected() function
-- #param subject The email's subject
-- #param body The email's body
function send_email(subject,body)
count = 0
email_subject = subject
email_body = body
smtp_socket = net.createConnection(net.TCP,0)
smtp_socket:on("connection",connected)
smtp_socket:on("receive",display)
smtp_socket:connect(SMTP_PORT, SMTP_SERVER)
end
-- Send an email
send_email("ESP8266", "[[Hi, How are your IoT projects coming along? Best Wishes,ESP8266]]")
However, I want to use a loop to monitor an analog input value and only send the email when certain analog input values are detected. Therefore, I added this code at the end of the script, after the sendemail() function definition and immediately before the function sendmail('subject', 'body') is called
vp = 0
gpio.mode(vp, gpio.INPUT)
while true do
local v = adc.read(vp)
if v < 840 or v > 870 then
print(v)
break
end
tmr.wdclr()
end
sendmail('subject', 'body')
The while loop works perfectly, waiting indefinitely for input from the analog pin. Once that input is found, it breaks correctly and calls the sendmail function. However, once that function is called, NodeMCU eventually resets. Sometimes it will get as far as successfully authenticating the SMTP credentials with the server, and sometimes it will not even make the HELO before it shuts down. What could possibly be causing this? Why would the sendmail.lua script work fine then suddenly decide not to work when adding this one small while loop that appears to work perfectly fine on its own?
A little quote from the NodeMCU reference:
tmr.wdclr() Feed the system watchdog.
In general, if you ever need to use this function, you are doing it
wrong.
The event-driven model of NodeMCU means that there is no need to be
sitting in hard loops waiting for things to occur. Rather, simply use
the callbacks to get notified when somethings happens. With this
approach, there should never be a need to manually feed the system
watchdog.
Please note the second line. :)
Not sure what your problem is, but why do you use a while loop in the first place? Why not use timer events to poll your ADC regularly?
Maybe the watchdog is triggered because your feed comes to late for some reason. In the if case you don't feed it at all befor you leave the loop.
Even if it may not be the definite answer I post it as such since the comment input is too small.
First, I suggest you use the script I posted for your previous question. This one isn't handling WiFi setup correctly. You need to wait in a timer until the device got an IP before you can continue. Remember, wifi.sta.config is non-blocking. And since it uses auto-connect=true if not set explicitly it'll try to connect to the AP immediately. That's also the reason why wifi.sta.autoconnect(1) is superfluous.
I don't understand the ADC reading code you posted.
vp = 0
gpio.mode(vp, gpio.INPUT)
Seems unnecessary to me because a) you don't do anything with GPIO 0 and b) adc.read only supports 0.
Rather than using a busy loop and constantly feeding the watch dog, which is a very bad sign, I suggest you use an interval based timer. Furthermore, I guess you don't wanna break the loop the first time the condition is met and never come back? So, you need to stay in the loop and keep triggering send mail, no? Something like this maybe (untested):
tmr.alarm(0, 200, tmr.ALARM_AUTO, function()
local v = adc.read(0)
if v < 840 or v > 870 then
node.task.post(function()
send_email("ESP8266", "[[Hi, How are your IoT projects coming along? Best Wishes,ESP8266]]")
end)
end
end)

Resources