File: client-lua.lp

package info (click to toggle)
gringo 4.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,260 kB
  • ctags: 10,755
  • sloc: cpp: 55,049; python: 629; yacc: 569; sh: 124; makefile: 23
file content (74 lines) | stat: -rw-r--r-- 2,373 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#script (lua) 

function run(prg, conn)
    local States = {
        ["SOLVE"] = 1,
        ["IDLE"]  = 2,
    }
    local SolveResults = {
        [gringo.SolveResult.SAT]     = "SAT",
        [gringo.SolveResult.UNSAT]   = "UNSAT",
        [gringo.SolveResult.UNKNOWN] = "UNKNOWN",
    }
    local state = States.IDLE
    local k = 0
    prg:ground({{"pigeon", {}}, {"sleep",  {k}}})
    prg:assign_external(gringo.Fun("sleep", {k}), true)
    while true do
        local f, ret, msg, err
        if state == States.SOLVE then
            f = prg:solve_async(
                nil,
                function (model) conn:send("Answer: "..tostring(model).."\n") end, 
                function (ret, int)
                    local msg = "finish:"..SolveResults[ret]
                    if int then msg = msg..":INTERRUPTED" end
                    conn:send(msg.."\n") 
                end)
        end
        msg, err = conn:receive("*l")
        if msg == nil then error(err) end
        if state == States.SOLVE then
            f:interrupt()
            ret = f:get()
        else
            ret = gringo.SolveResult.UNKNOWN
        end
        if msg == "interrupt" then
            state = States.IDLE
        elseif msg == "exit" then
            return
        elseif msg == "less_pigeon_please" then
            prg:assign_external(gringo.Fun("p"), false)
            state = States.IDLE
        elseif msg == "more_pigeon_please" then
            prg:assign_external(gringo.Fun("p"), true)
            state = States.IDLE
        elseif msg == "solve" then
            state = States.SOLVE
        else error("unexpected message: " .. msg) end
        if ret ~= gringo.SolveResult.UNKNOWN then
            k = k + 1
            prg:ground({{"sleep",  {k}}})
            prg:release_external(gringo.Fun("sleep", {k-1}))
            prg:assign_external(gringo.Fun("sleep", {k}), true)
        end
    end
end

function main(prg)
    file = io.open(".controller.PORT", "r")
    if file == nil then error("apparently no server is running") end
    p = tonumber(file:read("*all"))
    file:close()
    os.remove(".controller.PORT")
    socket = require "socket"
    conn = socket.tcp()
    ret, err = conn:connect("127.0.0.1", p)
    if ret == nil then error(err) end
    ret, err = pcall(run, prg, conn)
    conn:close()
    if not ret then error(err) end
end

#end.