ericsteen

ericsteen

I am working on a Decentralized Autonomous System Framework (seeking contributors) to help bring Carl Hewitt’s/Stanford University’s vision of Scalable Intelligent Systems to fruition.

TLDR; The Automaton is a user-defined BT that is ticked ( the whole user-defined tree/subtree is ticked via the corresponding update function(sequence/selector) etc..) at regular intervals. The problem is that the update function for the behavior tree has to tick(update) the tree synchronously as it needs to perform a depth first traversal to check for status of each node to make decisions.

When I use Process.send_after it is printing the tree out of order. I am assuming it is due to asynchronicity because when I remove that call it ticks the tree in DFS order once. With the call to send_after it prints the first node again before ticking the entire tree. I have tried using handle_call but cannot send to self (tried the GenServer.reply trick to send a message via spawing a process but that is just faking a synchronous call).
I have read in several places that one should not use a recieve/after type loop in GenServer because it can mess up GenServer’s own receive loop underlying the callbacks.

Is there another way to achieve this or am I missing something?

defmodule Automaton do
  @moduledoc """
    This is the primary user control interface to the Automata system. The
    configration parameters are used to inject the appropriate modules into the
    user-defined nodes based on their node_type and other options.

    TODO: store any currently processing nodes so they can be ticked directly
    within the behaviour tree engine rather than per tick traversal of the entire
    tree. Zipper Tree?
  """

  alias Automaton.Behavior
  alias Automaton.CompositeServer
  alias Automaton.ComponentServer

  defmacro __using__(user_opts) do
    prepend =
      quote do
        # all nodes are Behavior's
        use Behavior, user_opts: unquote(user_opts)
      end

    c_types = CompositeServer.types()
    cn_types = ComponentServer.types()
    allowed_node_types = c_types ++ cn_types
    node_type = user_opts[:node_type]
    unless Enum.member?(allowed_node_types, node_type), do: raise("NodeTypeError")

    node_type =
      cond do
        Enum.member?(c_types, node_type) ->
          quote do: use(CompositeServer, user_opts: unquote(user_opts))

        Enum.member?(cn_types, node_type) ->
          quote do: use(ComponentServer, user_opts: unquote(user_opts))
      end

    control =
      quote do
        def tick(state) do
          new_state = if state.status != :bh_running, do: on_init(state), else: state

          status = update(new_state)

          if status != :bh_running do
            on_terminate(status)
          else
            schedule_next_tick(new_state.tick_freq)
          end

          [status, new_state]
        end

        def schedule_next_tick(ms_delay) do
          Process.send_after(self(), :scheduled_tick, ms_delay)
        end

        @impl GenServer
        def handle_call(:tick, _from, state) do
          [status, new_state] = tick(state)
          {:reply, status, new_state}
        end

        @impl GenServer
        def handle_info(:scheduled_tick, state) do
          [status, new_state] = tick(state)

          {:noreply, new_state}
        end
      end

    [prepend, node_type, control]
  end
end

Where the actual Composite that is printing out of order is as follows:

defmodule Automaton.Composite.Sequence do
  @moduledoc """
    Behavior for user-defined sequence actions. When the execution of a sequence
    node starts, then the node’s children are executed in succession from left
    to right, returning to its parent a status failure (or running) as soon as a
    child that returns failure (or running) is found. It returns success only
    when all the children return success. The purpose of the sequence node is to
    carry out the tasks that are defined by a strict sequence of sub-tasks, in
    which all have to succeed.

    A Sequence will return immediately with a failure status code when one of
    its children fails. As long as its children are succeeding, it will keep
    going. If it runs out of children, it will return in success.
  """
  alias Automaton.{Composite, Behavior}

  defmacro __using__(opts) do
    quote do
      @impl Behavior
      def update(%{workers: workers} = state) do
        {w, status} = tick_workers(workers)
        status
      end

      def tick_workers(workers) do
        Enum.reduce_while(workers, :ok, fn w, _acc ->
          status = GenServer.call(w, :tick, 10_000)

          # If the child fails, or keeps running, do the same.
          cond do
            status == :bh_running ->
              {:cont, {w, :bh_running}}

            status != :bh_success ->
              {:halt, {w, status}}
          end
        end)
      end
    end
  end
end

Thanks and please help us improve massively on computer-human interaction for the 2020’s!

Eric

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews