Implement `resource_update` celery node

pull/1004/head
Connor Rigby 2019-09-23 15:30:20 -07:00 committed by Connor Rigby
parent 5608f823be
commit 96574f2033
4 changed files with 45 additions and 26 deletions

View File

@ -854,7 +854,7 @@ defmodule FarmbotCeleryScript.Compiler do
FarmbotCeleryScript.SysCalls.resource_update(
unquote(compile_ast(kind)),
unquote(compile_ast(id)),
unquote(compile_ast(params))
unquote(Macro.escape(params))
)
end
end

View File

@ -222,6 +222,12 @@ defmodule FarmbotCore.Asset do
Repo.get_by(Point, params)
end
def update_point(point, params) do
point
|> Point.changeset(params)
|> Repo.update()
end
## End Point
## Begin PublicKey

View File

@ -19,12 +19,13 @@ defmodule FarmbotOS.SysCalls do
FlashFirmware,
SendMessage,
SetPinIOMode,
PinControl
PinControl,
ResourceUpdate
}
alias FarmbotOS.Lua
alias FarmbotCore.{Asset, Asset.Repo, Asset.Private, Asset.Sync, BotState, Leds}
alias FarmbotCore.{Asset, Asset.Private, Asset.Sync, BotState, Leds}
alias FarmbotExt.{API, API.Reconciler, API.SyncGroup}
@behaviour FarmbotCeleryScript.SysCalls
@ -75,6 +76,9 @@ defmodule FarmbotOS.SysCalls do
@impl true
defdelegate toggle_pin(number), to: PinControl
@impl true
defdelegate resource_update(kind, id, params), to: ResourceUpdate
@impl true
def log(message, force?) do
if force? || FarmbotCore.Asset.fbos_config(:sequence_body_log) do
@ -122,29 +126,6 @@ defmodule FarmbotOS.SysCalls do
GenServer.stop(FarmbotFirmware, :reboot)
end
@impl true
def resource_update(kind, id, params) do
module = Module.concat(Asset, kind)
with true <- Code.ensure_loaded?(module),
%{} = orig <- Repo.get_by(module, [id: id], preload: [:local_meta]),
%{valid?: true} = change <- module.changeset(orig, params),
{:ok, new} <- Repo.update(change),
new <- Repo.preload(new, [:local_meta]) do
Private.mark_dirty!(new, %{})
:ok
else
false ->
{:error, "unknown asset kind: #{kind}"}
nil ->
{:error, "Could not find asset by kind: #{kind} and id: #{id}"}
%{valid?: false} = changeset ->
{:error, "failed to update #{kind}: #{inspect(changeset.errors)}"}
end
end
@impl true
def set_user_env(key, value) do
with {:ok, fwe} <- Asset.new_farmware_env(%{key: key, value: value}),

View File

@ -0,0 +1,32 @@
defmodule FarmbotOS.SysCalls.ResourceUpdate do
alias FarmbotCore.{
Asset,
Asset.Private
}
def resource_update("Device", 0, params) do
params
|> Asset.update_device!()
|> Private.mark_dirty!()
:ok
end
def resource_update("Plant", id, params) do
with %{} = plant <- Asset.get_point(pointer_type: "Plant", id: id),
{:ok, plant} <- Asset.update_point(plant, params) do
_ = Private.mark_dirty!(plant)
:ok
else
nil -> {:error, "Plant.#{id} is not currently synced, so it could not be updated"}
{:error, _changeset} -> {:error, "Failed to update Plant.#{id}"}
end
end
def resource_update(kind, id, _params) do
{:error,
"""
Unknown resource: #{kind}.#{id}
"""}
end
end