BeagleBone.jl~ 2.17 KB
Newer Older
Marcus Greiff's avatar
Marcus Greiff committed
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
75
76
77
78
79
80
81
82
83
84
85
86
# Devices should define a type `T` with methods:
# write!(::T, identifier, val)
# read(::T, identifier)

include("Debug.jl")
include("SysLED.jl")
include("GPIO.jl")

#List of available devices and their constructors
const DEVICES = Dict("debug" => Debug(), "sysled" => SysLED(), "gpio" => GPIO())

"""
    dev = getdev(devname)
    Gets the device corresponding to the name `devname`
"""
function getdev(devname)
    dev = try
        DEVICES[devname]
    catch
        error("Device $devname does not exist")
    end
    return dev
end

"""
    bbparse(cmd)
Parse and execute the command `cmd`
"""
bbparse(any) = error("Unexpected input: $any")

"""
    bbparse(l::Tuple)
Parse input on the form `l=(iswrite, ndev, cmd1, cmd2, ..., cmdn)``
where if `iswrite`
    `cmdi = (devname, id, val)`
    and if not `iswrite`
    `cmdi = (devname, id)`
"""
function bbparse(l::Tuple)
    iswrite = l[1]::Bool            #True if write command, false if read
    ndev = l[2]::Int32              #Number of devices/commands
    for i = 1:ndev
        command = l[2+i]::Tuple
        dev = getdev(command[1])
        if iswrite
            write!(dev, command[2], command[3])
        else
            val = read(dev, command[2])
            println("$val")
            #TODO return somewhere
        end
    end
end

"""
    run_server(port=2001)
Run a server on `port` that listens for commands from computer
"""
function run_server(port=2001)
    server = listen(port)
    @async while isopen(server)
        try
            sock = accept(server)
            @async while isopen(sock)
                try
                    l = deserialize(sock);
                    println("deserialize: $l")
                    bbparse(l)
                catch err
                    if !isopen(sock) && isa(err, Base.EOFError)
                        println("Connection to server closed")
                    else
                        throw(err)
                    end
                end
            end
        catch err
            if isa(err,Base.UVError) && err.prefix == "accept"
                println("Server closed successfully")
            else
                throw(err)
            end
        end
    end
    return server
end