Last active
December 20, 2015 03:39
-
-
Save pragdave/6065316 to your computer and use it in GitHub Desktop.
A simple DSL for gen_fsm. This generates regular gen_fsm functions (so, for example, each state/event combination is a separate function head)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Listen.NewFSM do | |
use Daves.Fsm, register: {:local, :listen_fsm}, | |
initial_state: :start, | |
init_params: [] | |
@timeout 3*1000 | |
defrecord CallInfo, from: "", to: "", suspicious_segments: 0 | |
#################### | |
# | |
# Events → our external API | |
events do | |
call_initiated(from, to) | |
suspicious_phrase_heard | |
hang_up | |
end | |
#################### | |
# | |
# States → transitions we implement | |
in_state(:start) do | |
{ :call_initiated, from, to } -> | |
IO.puts "Initiating a call from #{from} to #{to}" | |
next_state(:listening, CallInfo.new(from: from, to: to)) | |
end | |
in_state(:listening) do | |
{ :hang_up } -> | |
debug("Hangup", context) | |
next_state(:start, nil) | |
{ :suspicious_phrase_heard } -> | |
debug("Heard something suspicious", context) | |
next_state(:transcribing, context.update_suspicious_segments(&1+1), @timeout) | |
end | |
in_state(:transcribing) do | |
{ :hang_up } -> | |
debug("Report on call", context) | |
next_state(:start, CallData.new) | |
{ :timeout } -> | |
next_state(:listening, context) | |
end | |
# Helpers | |
defp debug(msg, CallInfo[from: from, to: to, suspicious_segments: suspicious_segments]) do | |
IO.puts("Call from #{from} to #{to}: #{msg}") | |
if suspicious_segments > 0 do | |
IO.puts(" (suspicious_segments: #{suspicious_segments})") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment