Split project (keep common)
This commit is contained in:
parent
9bc75b9627
commit
96a64cf90d
68 changed files with 32 additions and 3502 deletions
|
|
@ -1,3 +0,0 @@
|
|||
[alias]
|
||||
format = "+nightly fmt"
|
||||
lint = "clippy --all-targets --all-features -- -D warnings"
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
#EMGAUWA_CONTROLLER__LOGGING__LEVEL=DEBUG
|
||||
|
||||
#EMGAUWA_CORE__LOGGING__LEVEL=DEBUG
|
||||
39
Cargo.toml
39
Cargo.toml
|
|
@ -1,7 +1,32 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"emgauwa-core",
|
||||
"emgauwa-controller",
|
||||
"emgauwa-common",
|
||||
]
|
||||
[package]
|
||||
name = "emgauwa-common"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
simple_logger = "4.2"
|
||||
log = "0.4"
|
||||
|
||||
config = "0.13"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "macros", "chrono"] }
|
||||
libsqlite3-sys = { version = "*", features = ["bundled"] }
|
||||
uuid = "1.6"
|
||||
futures = "0.3"
|
||||
libc = "0.2"
|
||||
|
||||
rppal = "0.17"
|
||||
rppal-pfd = "0.0.5"
|
||||
rppal-mcp23s17 = "0.0.3"
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
[build]
|
||||
pre-build = [
|
||||
"curl -Lo /usr/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64",
|
||||
"chmod +x /usr/bin/yq"
|
||||
]
|
||||
37
Makefile
37
Makefile
|
|
@ -3,40 +3,3 @@ sqlx:
|
|||
cargo sqlx database create
|
||||
cargo sqlx migrate run
|
||||
cargo sqlx prepare --workspace
|
||||
|
||||
build-rpi:
|
||||
cross build --target arm-unknown-linux-gnueabihf
|
||||
|
||||
emgauwa-%.json: config/%.pkl
|
||||
pkl eval -f json -o $@ $<
|
||||
|
||||
configs:
|
||||
$(MAKE) emgauwa-core.json
|
||||
$(MAKE) emgauwa-controller.json
|
||||
|
||||
clean:
|
||||
rm -f emgauwa-controller.json
|
||||
rm -f emgauwa-controller.sqlite
|
||||
rm -f emgauwa-core.json
|
||||
rm -f emgauwa-core.sqlite
|
||||
rm -f emgauwa-dev.sqlite
|
||||
|
||||
emgauwa-controller_%:
|
||||
$(TOOL) build --target $* --release --bin emgauwa-controller
|
||||
mkdir -p out/releases
|
||||
cp target/$*/release/emgauwa-controller out/releases/emgauwa-controller_$*
|
||||
|
||||
emgauwa-core_%:
|
||||
$(TOOL) build --target $* --release --bin emgauwa-core
|
||||
mkdir -p out/releases
|
||||
cp target/$*/release/emgauwa-core out/releases/emgauwa-core_$*
|
||||
|
||||
emgauwa_%:
|
||||
$(MAKE) emgauwa-controller_$*
|
||||
$(MAKE) emgauwa-core_$*
|
||||
|
||||
releases:
|
||||
$(MAKE) TOOL=cross emgauwa_arm-unknown-linux-gnueabihf
|
||||
$(MAKE) TOOL=cargo emgauwa_x86_64-unknown-linux-gnu
|
||||
$(MAKE) TOOL=cross emgauwa_x86_64-unknown-linux-musl
|
||||
|
||||
|
|
|
|||
875
api.v1.yaml
875
api.v1.yaml
|
|
@ -1,875 +0,0 @@
|
|||
openapi: 3.0.0
|
||||
info:
|
||||
contact:
|
||||
name: Tobias Reisinger
|
||||
url: 'https://git.serguzim.me/emgauwa/'
|
||||
title: Emgauwa API v1
|
||||
version: 0.5.0
|
||||
description: Server API to manage an Emgauwa system.
|
||||
servers:
|
||||
- url: 'http://localhost:4419'
|
||||
tags:
|
||||
- name: schedules
|
||||
- name: relays
|
||||
- name: controllers
|
||||
- name: tags
|
||||
- name: macros
|
||||
- name: websocket
|
||||
paths:
|
||||
/api/v1/schedules:
|
||||
get:
|
||||
summary: get all schedules
|
||||
description: Receive a list with all available schedules.
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
headers: { }
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
operationId: get-api-v1-schedules
|
||||
post:
|
||||
summary: add new schedule
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'201':
|
||||
description: Created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
operationId: post-api-v1-schedules
|
||||
description: Create a new schedule. A new unique id will be returned
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
description: The "id" field will be set by the server.
|
||||
parameters: [ ]
|
||||
'/api/v1/schedules/{schedule_id}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
format: uuid
|
||||
name: schedule_id
|
||||
in: path
|
||||
required: true
|
||||
description: ''
|
||||
get:
|
||||
summary: get single schedule
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: get-schedules-schedule_id
|
||||
description: Return a single schedule by id.
|
||||
put:
|
||||
summary: overwrite single schedule
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
'400':
|
||||
description: Bad Request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: put-schedules-schedule_id
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
periods:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/period'
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/tag'
|
||||
description: ''
|
||||
parameters: [ ]
|
||||
description: Overwrite the properties for a single schedule. Overwriting periods on "on" or "off" will fail.
|
||||
delete:
|
||||
summary: delete single schedule
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
'403':
|
||||
description: Forbidden
|
||||
'404':
|
||||
description: Not Found
|
||||
operationId: delete-schedules-schedule_id
|
||||
description: Deletes a single schedule. Deleting "on" or "off" is forbidden (403).
|
||||
'/api/v1/schedules/tag/{tag}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: tag
|
||||
in: path
|
||||
required: true
|
||||
description: ''
|
||||
get:
|
||||
summary: get schedules by tag
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
operationId: get-schedules-tag-schedule_id
|
||||
description: Receive a list of schedules which include the given tag.
|
||||
/api/v1/relays:
|
||||
get:
|
||||
summary: get all relays
|
||||
tags:
|
||||
- relays
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
headers: { }
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
operationId: get-relays
|
||||
description: Return a list with all relays.
|
||||
parameters: [ ]
|
||||
'/api/v1/relays/tag/{tag}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: tag
|
||||
in: path
|
||||
required: true
|
||||
get:
|
||||
summary: get relays by tag
|
||||
tags:
|
||||
- relays
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
operationId: get-relays-tag-tag
|
||||
description: Return all relays with the given tag.
|
||||
/api/v1/controllers:
|
||||
get:
|
||||
summary: get all controllers
|
||||
tags:
|
||||
- controllers
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/controller'
|
||||
operationId: get-controllers
|
||||
description: Return all controllers.
|
||||
parameters: [ ]
|
||||
'/api/v1/controllers/{controller_id}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: controller_id
|
||||
in: path
|
||||
description: ''
|
||||
required: true
|
||||
get:
|
||||
summary: get single controller
|
||||
tags:
|
||||
- controllers
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/controller'
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: get-controllers-controller_id
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
description: ''
|
||||
description: Return a single controller by id. When no controller with the id is found 404 will be returned.
|
||||
put:
|
||||
summary: overwrite single controller
|
||||
tags:
|
||||
- controllers
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/controller'
|
||||
'400':
|
||||
description: Bad Request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: put-controllers-controller_id
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
ip:
|
||||
type: string
|
||||
format: ipv4
|
||||
description: Overwrite properties of a single controller.
|
||||
delete:
|
||||
summary: delete single controller
|
||||
tags:
|
||||
- controllers
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
'404':
|
||||
description: Not Found
|
||||
operationId: delete-controllers-controller_id
|
||||
description: Delete a single controller. To recover the controller you need to use the controllers/discover feature.
|
||||
'/api/v1/controllers/{controller_id}/relays':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: controller_id
|
||||
in: path
|
||||
required: true
|
||||
get:
|
||||
summary: get all relays for single controller
|
||||
tags:
|
||||
- controllers
|
||||
- relays
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
headers: { }
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items: { }
|
||||
operationId: get-controllers-controller_id-relays
|
||||
description: Returns all relays for a single controller.
|
||||
'/api/v1/controllers/{controller_id}/relays/{relay_num}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: controller_id
|
||||
in: path
|
||||
required: true
|
||||
- schema:
|
||||
type: integer
|
||||
name: relay_num
|
||||
in: path
|
||||
required: true
|
||||
get:
|
||||
summary: get single relay for single controller
|
||||
tags:
|
||||
- controllers
|
||||
- relays
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/relay'
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: get-controllers-controller_id-relays-relay_num
|
||||
description: 'Return a single relay by number for a controller by id. When the relay or controller is not found, 404 will be returned.'
|
||||
put:
|
||||
summary: overwrite single relay for single controller
|
||||
tags:
|
||||
- controllers
|
||||
- relays
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/relay'
|
||||
'400':
|
||||
description: Bad Request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
'404':
|
||||
description: Not Found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties: { }
|
||||
operationId: put-controllers-controller_id-relays-relay_num
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
active_schedule:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
schedules:
|
||||
type: array
|
||||
maxItems: 7
|
||||
minItems: 7
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/tag'
|
||||
description: 'active schedule will overwrite schedules[weekday]'
|
||||
/api/v1/tags:
|
||||
get:
|
||||
summary: get all tags
|
||||
tags:
|
||||
- tags
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/tag'
|
||||
operationId: get-tags
|
||||
description: Returns a list of tags.
|
||||
parameters: [ ]
|
||||
post:
|
||||
summary: add new tag
|
||||
operationId: post-api-v1-tags
|
||||
responses:
|
||||
'201':
|
||||
description: Created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/tag_full'
|
||||
'400':
|
||||
description: Bad Request
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
tag:
|
||||
$ref: '#/components/schemas/tag'
|
||||
description: ''
|
||||
tags:
|
||||
- tags
|
||||
description: Add a new tag. Will return 400 when the tag already exits.
|
||||
'/api/v1/tags/{tag}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: tag
|
||||
in: path
|
||||
required: true
|
||||
get:
|
||||
summary: get relays and schedules for tag
|
||||
tags:
|
||||
- tags
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/tag_full'
|
||||
'404':
|
||||
description: Not Found
|
||||
operationId: get-tags-tag
|
||||
description: Return all models with the given tag (relays and schedules)
|
||||
delete:
|
||||
summary: delete tag
|
||||
operationId: delete-tags-tag
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
'404':
|
||||
description: Not Found
|
||||
description: delete tag from database and from affected relays and schedules
|
||||
tags:
|
||||
- tags
|
||||
'/api/v1/controllers/{controller_id}/relays/{relay_num}/pulse':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: controller_id
|
||||
in: path
|
||||
required: true
|
||||
- schema:
|
||||
type: string
|
||||
name: relay_num
|
||||
in: path
|
||||
required: true
|
||||
post:
|
||||
summary: pulse relay on
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
'404':
|
||||
description: Not Found
|
||||
operationId: post-controllers-controller_id-relays-relay_num-pulse
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
duration:
|
||||
type: integer
|
||||
description: ''
|
||||
description: Turn a relay on for a short amount of time. The duration can be set in the body in seconds. When no duration is supplied the default for the relay will be used. The default is read from the controller's config.
|
||||
tags:
|
||||
- controllers
|
||||
- relays
|
||||
/api/v1/ws/relays:
|
||||
get:
|
||||
summary: get relay status updates
|
||||
tags:
|
||||
- websocket
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
operationId: get-ws-relays
|
||||
description: |-
|
||||
WEBSOCKET
|
||||
This websocket will send all relays with the most recent status every 10 seconds.
|
||||
parameters: [ ]
|
||||
/api/v1/macros:
|
||||
get:
|
||||
summary: get all macros
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/macro'
|
||||
operationId: get-api-v1-macros
|
||||
description: Receive a list with all available macros.
|
||||
post:
|
||||
summary: add new macro
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'201':
|
||||
description: Created
|
||||
operationId: post-api-v1-macros
|
||||
description: Create a new macro. A new unique id will be returned
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
actions:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
weekday:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 6
|
||||
relay:
|
||||
type: object
|
||||
properties:
|
||||
number:
|
||||
type: integer
|
||||
controller_id:
|
||||
$ref: '#/components/schemas/controller_id'
|
||||
schedule:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
'/api/v1/macros/{macro_id}':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: macro_id
|
||||
in: path
|
||||
required: true
|
||||
get:
|
||||
summary: get a single macro
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/macro'
|
||||
operationId: get-api-v1-macros-macro_id
|
||||
description: Return a single macro by id. When no macro with the id is found 404 will be returned.
|
||||
put:
|
||||
summary: overwrite a macro
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/macro'
|
||||
operationId: put-api-v1-macros-macro_id
|
||||
description: Overwrite properties of a single macro.
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
actions:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
weekday:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 6
|
||||
schedule:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
relay:
|
||||
type: object
|
||||
properties:
|
||||
number:
|
||||
type: integer
|
||||
controller_id:
|
||||
$ref: '#/components/schemas/controller_id'
|
||||
delete:
|
||||
summary: delete a macro
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
operationId: delete-api-v1-macros-macro_id
|
||||
description: Delete a single macro.
|
||||
'/api/v1/macros/{macro_id}/execute':
|
||||
parameters:
|
||||
- schema:
|
||||
type: string
|
||||
name: macro_id
|
||||
in: path
|
||||
required: true
|
||||
- schema:
|
||||
type: integer
|
||||
name: weekday
|
||||
in: query
|
||||
put:
|
||||
summary: execute a macro
|
||||
tags:
|
||||
- macros
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
'404':
|
||||
description: Not Found
|
||||
operationId: put-api-v1-macros-macro_id-execute
|
||||
description: Execute a macro
|
||||
/api/v1/schedules/list:
|
||||
post:
|
||||
summary: add new schedule list
|
||||
tags:
|
||||
- schedules
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
operationId: post-schedules-list
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
description: Create a list of schedules
|
||||
parameters: [ ]
|
||||
components:
|
||||
schemas:
|
||||
controller:
|
||||
title: controller
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/controller_id'
|
||||
name:
|
||||
type: string
|
||||
example: Garden Controller
|
||||
ip:
|
||||
type: string
|
||||
format: ipv4
|
||||
example: 224.73.153.12
|
||||
active:
|
||||
type: boolean
|
||||
port:
|
||||
type: integer
|
||||
example: 27480
|
||||
relay_count:
|
||||
type: integer
|
||||
minimum: 0
|
||||
example: 10
|
||||
relays:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
relay:
|
||||
title: relay
|
||||
type: object
|
||||
properties:
|
||||
number:
|
||||
type: integer
|
||||
minimum: 0
|
||||
example: 3
|
||||
name:
|
||||
type: string
|
||||
example: Sprinkling System 1
|
||||
controller_id:
|
||||
$ref: '#/components/schemas/controller_id'
|
||||
active_schedule:
|
||||
$ref: '#/components/schemas/schedule-untagged'
|
||||
schedules:
|
||||
type: array
|
||||
maxItems: 7
|
||||
minItems: 7
|
||||
items:
|
||||
$ref: '#/components/schemas/schedule-untagged'
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/tag'
|
||||
is_on:
|
||||
type: boolean
|
||||
description: NULL when unknown
|
||||
schedule-untagged:
|
||||
title: schedule
|
||||
type: object
|
||||
description: ''
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
name:
|
||||
type: string
|
||||
example: Sprinkler Sunny Day
|
||||
periods:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/period'
|
||||
schedule:
|
||||
title: schedule
|
||||
type: object
|
||||
description: ''
|
||||
properties:
|
||||
id:
|
||||
$ref: '#/components/schemas/schedule_id'
|
||||
name:
|
||||
type: string
|
||||
example: Sprinkler Sunny Day
|
||||
periods:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/period'
|
||||
tags:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/tag'
|
||||
period:
|
||||
title: period
|
||||
type: object
|
||||
properties:
|
||||
start:
|
||||
type: string
|
||||
example: '10:15'
|
||||
format: 24-hour
|
||||
end:
|
||||
type: string
|
||||
format: 24-hour
|
||||
example: '14:45'
|
||||
required:
|
||||
- start
|
||||
- end
|
||||
controller_id:
|
||||
type: string
|
||||
title: controller_id
|
||||
format: uuid
|
||||
example: 589c0eab-a4b4-4f3a-be97-cf03b1dc8edc
|
||||
tag:
|
||||
type: string
|
||||
title: tag
|
||||
example: sprinkler
|
||||
tag_full:
|
||||
title: tag (full)
|
||||
type: object
|
||||
properties:
|
||||
tag:
|
||||
$ref: '#/components/schemas/tag'
|
||||
relays:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/relay'
|
||||
schedules:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
schedule_id:
|
||||
type: string
|
||||
title: schedule_id
|
||||
format: uuid
|
||||
example: 6bceb29b-7d2e-4af3-a26e-11f514dc5cc1
|
||||
macro:
|
||||
title: macro
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
example: a9a4eab4-6c54-4fe4-b755-bdb2a90b3242
|
||||
name:
|
||||
type: string
|
||||
actions:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/macro_action'
|
||||
macro_action:
|
||||
title: macro_action
|
||||
type: object
|
||||
description: ''
|
||||
properties:
|
||||
weekday:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 6
|
||||
schedule:
|
||||
$ref: '#/components/schemas/schedule'
|
||||
relay:
|
||||
$ref: '#/components/schemas/relay'
|
||||
required:
|
||||
- weekday
|
||||
- schedule
|
||||
- relay
|
||||
3
build.rs
Normal file
3
build.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
amends "package://emgauwa.app/pkl/emgauwa@0.1.0#/controller.pkl"
|
||||
|
||||
relays {
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 0
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 1
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 2
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 3
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 4
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 5
|
||||
inverted = true
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 10
|
||||
inverted = true
|
||||
pulse = 10
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 11
|
||||
inverted = true
|
||||
pulse = 10
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 20
|
||||
inverted = false
|
||||
}
|
||||
new {
|
||||
driver = "null"
|
||||
pin = 21
|
||||
inverted = false
|
||||
}
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
amends "package://emgauwa.app/pkl/emgauwa@0.1.0#/core.pkl"
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
[package]
|
||||
name = "emgauwa-common"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
simple_logger = "4.2"
|
||||
log = "0.4"
|
||||
|
||||
config = "0.13"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "macros", "chrono"] }
|
||||
libsqlite3-sys = { version = "*", features = ["bundled"] }
|
||||
uuid = "1.6"
|
||||
futures = "0.3"
|
||||
libc = "0.2"
|
||||
|
||||
rppal = "0.17"
|
||||
rppal-pfd = "0.0.5"
|
||||
rppal-mcp23s17 = "0.0.3"
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
[package]
|
||||
name = "emgauwa-controller"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
[dependencies]
|
||||
emgauwa-common = { path = "../emgauwa-common" }
|
||||
|
||||
actix = "0.13"
|
||||
|
||||
tokio = { version = "1.34", features = ["io-std", "macros", "rt-multi-thread"] }
|
||||
tokio-tungstenite = "0.21"
|
||||
|
||||
simple_logger = "4.3"
|
||||
log = "0.4"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.5", features = ["serde", "v4"] }
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "macros", "chrono"] }
|
||||
|
||||
futures = "0.3"
|
||||
futures-channel = "0.3"
|
||||
|
||||
rppal = "0.17"
|
||||
rppal-pfd = "0.0.5"
|
||||
rppal-mcp23s17 = "0.0.3"
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix::{Actor, Context, Handler, Message};
|
||||
use emgauwa_common::constants;
|
||||
use emgauwa_common::drivers::RelayDriver;
|
||||
use emgauwa_common::errors::EmgauwaError;
|
||||
use emgauwa_common::models::Controller;
|
||||
use emgauwa_common::types::RelayStates;
|
||||
use futures::executor::block_on;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::settings::Settings;
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Result<(), EmgauwaError>")]
|
||||
pub struct Reload {}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct UpdateRelayStates {
|
||||
pub relay_states: RelayStates,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Result<(), EmgauwaError>")]
|
||||
pub struct RelayPulse {
|
||||
pub relay_number: i64,
|
||||
pub duration: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Controller")]
|
||||
pub struct GetThis {}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Arc<Notify>")]
|
||||
pub struct GetControllerNotifier {}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "Arc<Notify>")]
|
||||
pub struct GetRelayNotifier {}
|
||||
|
||||
pub struct AppState {
|
||||
pub pool: Pool<Sqlite>,
|
||||
pub this: Controller,
|
||||
pub settings: Settings,
|
||||
pub drivers: Vec<Box<dyn RelayDriver>>,
|
||||
pub controller_notifier: Arc<Notify>,
|
||||
pub relay_notifier: Arc<Notify>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(
|
||||
pool: Pool<Sqlite>,
|
||||
this: Controller,
|
||||
settings: Settings,
|
||||
drivers: Vec<Box<dyn RelayDriver>>,
|
||||
) -> AppState {
|
||||
AppState {
|
||||
pool,
|
||||
this,
|
||||
settings,
|
||||
drivers,
|
||||
controller_notifier: Arc::new(Notify::new()),
|
||||
relay_notifier: Arc::new(Notify::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn notify_controller_change(&self) {
|
||||
self.controller_notifier.notify_one();
|
||||
}
|
||||
|
||||
pub fn notify_relay_change(&self) {
|
||||
self.relay_notifier.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for AppState {
|
||||
type Context = Context<Self>;
|
||||
}
|
||||
|
||||
impl Handler<Reload> for AppState {
|
||||
type Result = Result<(), EmgauwaError>;
|
||||
|
||||
fn handle(&mut self, _msg: Reload, _ctx: &mut Self::Context) -> Self::Result {
|
||||
log::debug!("Reloading controller");
|
||||
let mut pool_conn = block_on(self.pool.acquire())?;
|
||||
|
||||
self.this.reload(&mut pool_conn)?;
|
||||
|
||||
self.notify_controller_change();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<UpdateRelayStates> for AppState {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, msg: UpdateRelayStates, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.this.apply_relay_states(&msg.relay_states);
|
||||
self.drivers
|
||||
.iter_mut()
|
||||
.zip(msg.relay_states.iter())
|
||||
.for_each(|(driver, state)| {
|
||||
if let Err(e) = driver.set(state.unwrap_or(false)) {
|
||||
log::error!("Error setting relay: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
self.notify_relay_change();
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<RelayPulse> for AppState {
|
||||
type Result = Result<(), EmgauwaError>;
|
||||
|
||||
fn handle(&mut self, msg: RelayPulse, _ctx: &mut Self::Context) -> Self::Result {
|
||||
let relay_num = msg.relay_number;
|
||||
|
||||
let duration = Duration::from_secs(
|
||||
match msg.duration {
|
||||
None => {
|
||||
self.settings
|
||||
.get_relay(relay_num)
|
||||
.ok_or(EmgauwaError::Other(String::from(
|
||||
"Relay not found in settings",
|
||||
)))?
|
||||
.pulse
|
||||
}
|
||||
Some(dur) => Some(dur as u64),
|
||||
}
|
||||
.unwrap_or(constants::RELAY_PULSE_DURATION),
|
||||
);
|
||||
let now = Instant::now();
|
||||
let until = now + duration;
|
||||
|
||||
self.this.relay_pulse(relay_num, until)?;
|
||||
log::debug!(
|
||||
"Pulsing relay {} for {} seconds until {:?}",
|
||||
relay_num,
|
||||
duration.as_secs(),
|
||||
until
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<GetThis> for AppState {
|
||||
type Result = Controller;
|
||||
|
||||
fn handle(&mut self, _msg: GetThis, _ctx: &mut Self::Context) -> Self::Result {
|
||||
self.this.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<GetControllerNotifier> for AppState {
|
||||
type Result = Arc<Notify>;
|
||||
|
||||
fn handle(&mut self, _msg: GetControllerNotifier, _ctx: &mut Self::Context) -> Self::Result {
|
||||
Arc::clone(&self.controller_notifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<GetRelayNotifier> for AppState {
|
||||
type Result = Arc<Notify>;
|
||||
|
||||
fn handle(&mut self, _msg: GetRelayNotifier, _ctx: &mut Self::Context) -> Self::Result {
|
||||
Arc::clone(&self.relay_notifier)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Driver {
|
||||
Null,
|
||||
Gpio,
|
||||
PiFace,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Driver {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
match String::deserialize(deserializer)?.as_str() {
|
||||
"null" => Ok(Driver::Null),
|
||||
"gpio" => Ok(Driver::Gpio),
|
||||
"piface" => Ok(Driver::PiFace),
|
||||
_ => Err(serde::de::Error::custom("invalid driver")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,124 +0,0 @@
|
|||
use actix::Actor;
|
||||
use emgauwa_common::db;
|
||||
use emgauwa_common::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
||||
use emgauwa_common::errors::EmgauwaError;
|
||||
use emgauwa_common::models::{Controller, FromDbModel};
|
||||
use emgauwa_common::types::EmgauwaUid;
|
||||
use emgauwa_common::utils::{drop_privileges, init_logging};
|
||||
use rppal_pfd::PiFaceDigital;
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::Sqlite;
|
||||
|
||||
use crate::relay_loop::run_relays_loop;
|
||||
use crate::settings::Settings;
|
||||
use crate::ws::run_ws_loop;
|
||||
|
||||
mod app_state;
|
||||
mod driver;
|
||||
mod relay_loop;
|
||||
mod settings;
|
||||
mod utils;
|
||||
mod ws;
|
||||
|
||||
async fn create_this_controller(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
settings: &Settings,
|
||||
) -> Result<DbController, EmgauwaError> {
|
||||
DbController::create(
|
||||
conn,
|
||||
&EmgauwaUid::default(),
|
||||
&settings.name,
|
||||
settings.relays.len() as i64,
|
||||
)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)
|
||||
}
|
||||
|
||||
async fn create_this_relay(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
this_controller: &DbController,
|
||||
settings_relay: &settings::Relay,
|
||||
) -> Result<DbRelay, EmgauwaError> {
|
||||
let relay = DbRelay::create(
|
||||
conn,
|
||||
&settings_relay.name,
|
||||
settings_relay.number.ok_or(EmgauwaError::Internal(
|
||||
"Relay number is missing".to_string(),
|
||||
))?,
|
||||
this_controller,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let off = DbSchedule::get_off(conn).await?;
|
||||
for weekday in 0..7 {
|
||||
DbJunctionRelaySchedule::set_schedule(conn, &relay, &off, weekday).await?;
|
||||
}
|
||||
|
||||
Ok(relay)
|
||||
}
|
||||
|
||||
#[actix::main]
|
||||
async fn main() -> Result<(), std::io::Error> {
|
||||
let settings = settings::init()?;
|
||||
|
||||
drop_privileges(&settings.permissions)?;
|
||||
|
||||
init_logging(&settings.logging.level)?;
|
||||
|
||||
let mut pfd: Option<PiFaceDigital> = None;
|
||||
let drivers = settings.relays_make_drivers(&mut pfd)?;
|
||||
|
||||
let pool = db::init(&settings.database)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?;
|
||||
|
||||
let mut conn = pool.acquire().await.map_err(EmgauwaError::from)?;
|
||||
|
||||
let db_controller = match DbController::get_all(&mut conn)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?
|
||||
.pop()
|
||||
{
|
||||
None => futures::executor::block_on(create_this_controller(&mut conn, &settings))?,
|
||||
Some(c) => c,
|
||||
};
|
||||
|
||||
for relay in &settings.relays {
|
||||
if DbRelay::get_by_controller_and_num(
|
||||
&mut conn,
|
||||
&db_controller,
|
||||
relay.number.ok_or(EmgauwaError::Internal(
|
||||
"Relay number is missing".to_string(),
|
||||
))?,
|
||||
)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?
|
||||
.is_none()
|
||||
{
|
||||
create_this_relay(&mut conn, &db_controller, relay)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?;
|
||||
}
|
||||
}
|
||||
|
||||
let db_controller = db_controller
|
||||
.update(&mut conn, &db_controller.name, settings.relays.len() as i64)
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?;
|
||||
|
||||
let this = Controller::from_db_model(&mut conn, db_controller).map_err(EmgauwaError::from)?;
|
||||
|
||||
let url = format!(
|
||||
"ws://{}:{}/api/v1/ws/controllers",
|
||||
settings.server.host, settings.server.port
|
||||
);
|
||||
|
||||
let app_state = app_state::AppState::new(pool.clone(), this, settings, drivers).start();
|
||||
|
||||
let _ = tokio::join!(
|
||||
tokio::spawn(run_relays_loop(app_state.clone())),
|
||||
tokio::spawn(run_ws_loop(pool.clone(), app_state.clone(), url)),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix::Addr;
|
||||
use chrono::{Local, Timelike};
|
||||
use emgauwa_common::constants::RELAYS_RETRY_TIMEOUT;
|
||||
use emgauwa_common::errors::EmgauwaError;
|
||||
use emgauwa_common::models::Controller;
|
||||
use emgauwa_common::types::{RelayStates, Weekday};
|
||||
use emgauwa_common::utils::printable_relay_states;
|
||||
use futures::pin_mut;
|
||||
use tokio::time;
|
||||
use tokio::time::timeout;
|
||||
use utils::app_state_get_controller_notifier;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::utils;
|
||||
|
||||
pub async fn run_relays_loop(app_state: Addr<AppState>) {
|
||||
log::debug!("Spawned relays loop");
|
||||
loop {
|
||||
let run_result = run_relays(&app_state).await;
|
||||
if let Err(err) = run_result {
|
||||
log::error!("Error running relays: {}", err);
|
||||
}
|
||||
time::sleep(RELAYS_RETRY_TIMEOUT).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
|
||||
let notifier = &*app_state_get_controller_notifier(app_state).await?;
|
||||
|
||||
let mut last_weekday = emgauwa_common::utils::get_weekday();
|
||||
let mut this = utils::app_state_get_this(app_state).await?;
|
||||
let mut relay_states: RelayStates = Vec::new();
|
||||
init_relay_states(&mut relay_states, &this);
|
||||
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
|
||||
|
||||
let mut duration_override = None;
|
||||
|
||||
loop {
|
||||
log::debug!(
|
||||
"Relay loop at {}: {}",
|
||||
Local::now().naive_local().time(),
|
||||
printable_relay_states(&this.get_relay_states())
|
||||
);
|
||||
|
||||
let notifier_future = notifier.notified();
|
||||
pin_mut!(notifier_future);
|
||||
let mut changed = timeout(
|
||||
get_next_duration(&this, &mut duration_override),
|
||||
&mut notifier_future,
|
||||
)
|
||||
.await
|
||||
.is_ok();
|
||||
|
||||
check_weekday(app_state, &mut last_weekday, &mut changed).await?;
|
||||
|
||||
if changed {
|
||||
log::debug!("Reloading controller in relay loop");
|
||||
this = utils::app_state_get_this(app_state).await?;
|
||||
}
|
||||
|
||||
let now_pulse = Instant::now();
|
||||
duration_override = this
|
||||
.relays
|
||||
.iter_mut()
|
||||
.filter_map(|relay| match relay.check_pulsing(&now_pulse) {
|
||||
None => None,
|
||||
Some(pulse) => {
|
||||
let dur = pulse - now_pulse;
|
||||
log::debug!(
|
||||
"Pulsing relay {} for {}s until {:?} ",
|
||||
relay.r.number,
|
||||
dur.as_secs(),
|
||||
pulse
|
||||
);
|
||||
Some(dur)
|
||||
}
|
||||
})
|
||||
.min();
|
||||
|
||||
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
|
||||
}
|
||||
}
|
||||
|
||||
fn init_relay_states(relay_states: &mut RelayStates, this: &Controller) {
|
||||
relay_states.clear();
|
||||
for _ in 0..this.c.relay_count {
|
||||
relay_states.push(None);
|
||||
}
|
||||
}
|
||||
|
||||
async fn calc_relay_states(
|
||||
relay_states: &mut RelayStates,
|
||||
this: &mut Controller,
|
||||
app_state: &Addr<AppState>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let now = Local::now().time();
|
||||
let now_pulse = Instant::now();
|
||||
|
||||
this.relays
|
||||
.iter_mut()
|
||||
.zip(relay_states.iter_mut())
|
||||
.for_each(|(relay, state)| {
|
||||
relay.is_on = Some(
|
||||
relay.active_schedule.is_on(&now) || relay.check_pulsing(&now_pulse).is_some(),
|
||||
);
|
||||
*state = relay.is_on;
|
||||
});
|
||||
utils::app_state_update_relays_on(app_state, relay_states.clone()).await
|
||||
}
|
||||
|
||||
fn get_next_duration(this: &Controller, duration_override: &mut Option<Duration>) -> Duration {
|
||||
if let Some(duration) = duration_override {
|
||||
log::debug!("Duration override. Waiting for {}s", duration.as_secs());
|
||||
return *duration;
|
||||
}
|
||||
|
||||
let now = Local::now().time();
|
||||
let now_in_s = now.num_seconds_from_midnight();
|
||||
let next_timestamp = this
|
||||
.get_next_time(&now)
|
||||
.map_or(86400, |t| t.num_seconds_from_midnight());
|
||||
|
||||
let duration_to_next = Duration::from_secs((next_timestamp - now_in_s) as u64);
|
||||
|
||||
log::debug!(
|
||||
"Next timestamp: {}; Waiting for {}s",
|
||||
next_timestamp,
|
||||
duration_to_next.as_secs()
|
||||
);
|
||||
|
||||
duration_to_next
|
||||
}
|
||||
|
||||
async fn check_weekday(
|
||||
app_state: &Addr<AppState>,
|
||||
last_weekday: &mut Weekday,
|
||||
changed: &mut bool,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let current_weekday = emgauwa_common::utils::get_weekday();
|
||||
if current_weekday.ne(last_weekday) {
|
||||
log::debug!("Weekday changed");
|
||||
*last_weekday = current_weekday;
|
||||
utils::app_state_reload(app_state).await?;
|
||||
*changed = true;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
use emgauwa_common::errors::EmgauwaError;
|
||||
use emgauwa_common::{drivers, settings};
|
||||
use rppal_pfd::PiFaceDigital;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use crate::driver::Driver;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[allow(unused)]
|
||||
pub struct Relay {
|
||||
pub driver: Driver,
|
||||
pub name: String,
|
||||
pub number: Option<i64>,
|
||||
pub pin: u8,
|
||||
pub inverted: bool,
|
||||
pub pulse: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[allow(unused)]
|
||||
pub struct Settings {
|
||||
pub server: settings::Server,
|
||||
pub database: String,
|
||||
pub permissions: settings::Permissions,
|
||||
pub logging: settings::Logging,
|
||||
|
||||
pub name: String,
|
||||
pub relays: Vec<Relay>,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Settings {
|
||||
server: settings::Server::default(),
|
||||
database: String::from("sqlite://emgauwa-controller.sqlite"),
|
||||
permissions: settings::Permissions::default(),
|
||||
logging: settings::Logging::default(),
|
||||
|
||||
name: String::from("Emgauwa Controller"),
|
||||
relays: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Relay {
|
||||
fn default() -> Self {
|
||||
Relay {
|
||||
driver: Driver::Gpio,
|
||||
number: None,
|
||||
name: String::from("Relay"),
|
||||
pin: 0,
|
||||
inverted: false,
|
||||
pulse: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init() -> Result<Settings, EmgauwaError> {
|
||||
let mut settings: Settings = settings::load("controller", "CONTROLLER")?;
|
||||
|
||||
for (num, relay) in settings.relays.iter_mut().enumerate() {
|
||||
if relay.number.is_none() {
|
||||
relay.number = Some(num as i64);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn get_relay(&self, number: i64) -> Option<&Relay> {
|
||||
self.relays.iter().find(|r| r.number == Some(number))
|
||||
}
|
||||
|
||||
pub fn relays_make_drivers(
|
||||
&self,
|
||||
pfd: &mut Option<PiFaceDigital>,
|
||||
) -> Result<Vec<Box<dyn drivers::RelayDriver>>, EmgauwaError> {
|
||||
let mut drivers = Vec::new();
|
||||
for relay in &self.relays {
|
||||
drivers.push(relay.make_driver(pfd)?);
|
||||
}
|
||||
Ok(drivers)
|
||||
}
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
pub fn make_driver(
|
||||
&self,
|
||||
pfd: &mut Option<PiFaceDigital>,
|
||||
) -> Result<Box<dyn drivers::RelayDriver>, EmgauwaError> {
|
||||
let driver: Box<dyn drivers::RelayDriver> = match self.driver {
|
||||
Driver::Null => Box::new(drivers::NullDriver::new(self.pin)),
|
||||
Driver::Gpio => Box::new(drivers::GpioDriver::new(self.pin, self.inverted)?),
|
||||
Driver::PiFace => {
|
||||
if pfd.is_none() {
|
||||
*pfd = Some(drivers::PiFaceDriver::init_piface()?);
|
||||
}
|
||||
Box::new(drivers::PiFaceDriver::new(self.pin, pfd)?)
|
||||
}
|
||||
};
|
||||
Ok(driver)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use actix::Addr;
|
||||
use emgauwa_common::errors::EmgauwaError;
|
||||
use emgauwa_common::models::Controller;
|
||||
use emgauwa_common::types::RelayStates;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::app_state;
|
||||
use crate::app_state::AppState;
|
||||
|
||||
pub async fn app_state_get_this(app_state: &Addr<AppState>) -> Result<Controller, EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::GetThis {})
|
||||
.await
|
||||
.map_err(EmgauwaError::from)
|
||||
}
|
||||
|
||||
pub async fn app_state_get_relay_notifier(
|
||||
app_state: &Addr<AppState>,
|
||||
) -> Result<Arc<Notify>, EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::GetRelayNotifier {})
|
||||
.await
|
||||
.map_err(EmgauwaError::from)
|
||||
}
|
||||
|
||||
pub async fn app_state_get_controller_notifier(
|
||||
app_state: &Addr<AppState>,
|
||||
) -> Result<Arc<Notify>, EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::GetControllerNotifier {})
|
||||
.await
|
||||
.map_err(EmgauwaError::from)
|
||||
}
|
||||
|
||||
pub async fn app_state_reload(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::Reload {})
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?
|
||||
}
|
||||
|
||||
pub async fn app_state_update_relays_on(
|
||||
app_state: &Addr<AppState>,
|
||||
relay_states: RelayStates,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::UpdateRelayStates { relay_states })
|
||||
.await
|
||||
.map_err(EmgauwaError::from)
|
||||
}
|
||||
|
||||
pub async fn app_state_relay_pulse(
|
||||
app_state: &Addr<AppState>,
|
||||
relay_number: i64,
|
||||
duration: Option<u32>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
app_state
|
||||
.send(app_state::RelayPulse {
|
||||
relay_number,
|
||||
duration,
|
||||
})
|
||||
.await
|
||||
.map_err(EmgauwaError::from)?
|
||||
}
|
||||
|
|
@ -1,247 +0,0 @@
|
|||
use actix::Addr;
|
||||
use emgauwa_common::constants::WEBSOCKET_RETRY_TIMEOUT;
|
||||
use emgauwa_common::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
||||
use emgauwa_common::errors::{DatabaseError, EmgauwaError};
|
||||
use emgauwa_common::models::{Controller, Relay};
|
||||
use emgauwa_common::types::{ControllerWsAction, ScheduleUid};
|
||||
use futures::{future, pin_mut, SinkExt, StreamExt};
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use tokio::time;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::{connect_async, tungstenite};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::utils;
|
||||
use crate::utils::{app_state_get_relay_notifier, app_state_get_this};
|
||||
|
||||
pub async fn run_ws_loop(pool: Pool<Sqlite>, app_state: Addr<AppState>, url: String) {
|
||||
log::debug!("Spawned ws loop");
|
||||
loop {
|
||||
let run_result = run_websocket(pool.clone(), &app_state, &url).await;
|
||||
if let Err(err) = run_result {
|
||||
log::error!("Error running websocket: {}", err);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Retrying to connect in {} seconds...",
|
||||
WEBSOCKET_RETRY_TIMEOUT.as_secs()
|
||||
);
|
||||
time::sleep(WEBSOCKET_RETRY_TIMEOUT).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_websocket(
|
||||
pool: Pool<Sqlite>,
|
||||
app_state: &Addr<AppState>,
|
||||
url: &str,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
log::debug!("Trying to connect to {}", url);
|
||||
match connect_async(url).await {
|
||||
Ok(connection) => {
|
||||
log::info!("Websocket connected");
|
||||
let (ws_stream, _) = connection;
|
||||
|
||||
let (mut write, read) = ws_stream.split();
|
||||
|
||||
let ws_action = ControllerWsAction::Register(app_state_get_this(app_state).await?);
|
||||
|
||||
let ws_action_json = serde_json::to_string(&ws_action)?;
|
||||
if let Err(err) = write.send(Message::text(ws_action_json)).await {
|
||||
log::error!("Failed to register at websocket: {}", err);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (app_state_tx, app_state_rx) = futures_channel::mpsc::unbounded::<Message>();
|
||||
tokio::spawn(read_app_state(app_state.clone(), app_state_tx));
|
||||
let app_state_to_ws = app_state_rx.map(Ok).forward(write);
|
||||
|
||||
let read_handler = read.for_each(|msg| handle_message(pool.clone(), app_state, msg));
|
||||
|
||||
pin_mut!(app_state_to_ws, read_handler);
|
||||
future::select(app_state_to_ws, read_handler).await;
|
||||
|
||||
log::warn!("Lost connection to websocket");
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Failed to connect to websocket: {}", err,);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_app_state(
|
||||
app_state: Addr<AppState>,
|
||||
tx: futures_channel::mpsc::UnboundedSender<Message>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let notifier = &*app_state_get_relay_notifier(&app_state).await?;
|
||||
loop {
|
||||
notifier.notified().await;
|
||||
log::debug!("Relay change detected");
|
||||
let this = app_state_get_this(&app_state).await?;
|
||||
let relay_states = this.get_relay_states();
|
||||
let ws_action = ControllerWsAction::RelayStates((this.c.uid, relay_states));
|
||||
|
||||
let ws_action_json = serde_json::to_string(&ws_action)?;
|
||||
tx.unbounded_send(Message::text(ws_action_json))
|
||||
.map_err(|_| {
|
||||
EmgauwaError::Other(String::from(
|
||||
"Failed to forward message from app state to websocket",
|
||||
))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_message(
|
||||
pool: Pool<Sqlite>,
|
||||
app_state: &Addr<AppState>,
|
||||
message_result: Result<Message, tungstenite::Error>,
|
||||
) {
|
||||
let msg = match message_result {
|
||||
Ok(msg) => msg,
|
||||
Err(err) => {
|
||||
log::error!("Error reading message: {}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Message::Text(text) = msg {
|
||||
match serde_json::from_str(&text) {
|
||||
Ok(action) => {
|
||||
log::debug!("Received action: {:?}", action);
|
||||
let mut pool_conn = match pool.acquire().await {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => {
|
||||
log::error!("Failed to acquire database connection: {:?}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let action_res = handle_action(&mut pool_conn, app_state, action).await;
|
||||
if let Err(e) = action_res {
|
||||
log::error!("Error handling action: {:?}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Error deserializing action: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_action(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
app_state: &Addr<AppState>,
|
||||
action: ControllerWsAction,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let this = app_state_get_this(app_state).await?;
|
||||
|
||||
match action {
|
||||
ControllerWsAction::Controller(controller) => {
|
||||
handle_controller(conn, &this, controller).await?
|
||||
}
|
||||
ControllerWsAction::Relays(relays) => handle_relays(conn, &this, relays).await?,
|
||||
ControllerWsAction::Schedules(schedules) => handle_schedules(conn, schedules).await?,
|
||||
ControllerWsAction::RelayPulse((relay_num, duration)) => {
|
||||
handle_relay_pulse(app_state, relay_num, duration).await?
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
|
||||
utils::app_state_reload(app_state).await
|
||||
}
|
||||
|
||||
async fn handle_controller(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
this: &Controller,
|
||||
controller: Controller,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
if controller.c.uid != this.c.uid {
|
||||
return Err(EmgauwaError::Other(String::from(
|
||||
"Controller UID mismatch during update",
|
||||
)));
|
||||
}
|
||||
DbController::get_by_uid(conn, &controller.c.uid)
|
||||
.await?
|
||||
.ok_or(DatabaseError::NotFound)?
|
||||
.update(conn, controller.c.name.as_str(), this.c.relay_count)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_schedules(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
schedules: Vec<DbSchedule>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let mut handled_uids = vec![
|
||||
// on and off schedules are always present and should not be updated
|
||||
ScheduleUid::On,
|
||||
ScheduleUid::Off,
|
||||
];
|
||||
for schedule in schedules {
|
||||
if handled_uids.contains(&schedule.uid) {
|
||||
continue;
|
||||
}
|
||||
handled_uids.push(schedule.uid.clone());
|
||||
|
||||
log::debug!("Handling schedule: {:?}", schedule);
|
||||
let schedule_db = DbSchedule::get_by_uid(conn, &schedule.uid).await?;
|
||||
|
||||
if let Some(schedule_db) = schedule_db {
|
||||
schedule_db
|
||||
.update(conn, schedule.name.as_str(), &schedule.periods)
|
||||
.await?;
|
||||
} else {
|
||||
DbSchedule::create(
|
||||
conn,
|
||||
schedule.uid.clone(),
|
||||
schedule.name.as_str(),
|
||||
&schedule.periods,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_relays(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
this: &Controller,
|
||||
relays: Vec<Relay>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
for relay in relays {
|
||||
if relay.controller.uid != this.c.uid {
|
||||
return Err(EmgauwaError::Other(String::from(
|
||||
"Controller UID mismatch during relay update",
|
||||
)));
|
||||
}
|
||||
let db_relay = DbRelay::get_by_controller_and_num(conn, &this.c, relay.r.number)
|
||||
.await?
|
||||
.ok_or(DatabaseError::NotFound)?;
|
||||
|
||||
db_relay.update(conn, relay.r.name.as_str()).await?;
|
||||
|
||||
handle_schedules(conn, relay.schedules.clone()).await?;
|
||||
|
||||
let mut schedules = Vec::new(); // We need to get the schedules from the database to have the right IDs
|
||||
for schedule in relay.schedules {
|
||||
schedules.push(
|
||||
DbSchedule::get_by_uid(conn, &schedule.uid)
|
||||
.await?
|
||||
.ok_or(DatabaseError::NotFound)?,
|
||||
);
|
||||
}
|
||||
|
||||
DbJunctionRelaySchedule::set_schedules(conn, &db_relay, schedules.iter().collect()).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_relay_pulse(
|
||||
app_state: &Addr<AppState>,
|
||||
relay_num: i64,
|
||||
duration: Option<u32>,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
utils::app_state_relay_pulse(app_state, relay_num, duration).await
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
[package]
|
||||
name = "emgauwa-core"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
authors = ["Tobias Reisinger <tobias@msrg.cc>"]
|
||||
|
||||
[dependencies]
|
||||
emgauwa-common = { path = "../emgauwa-common" }
|
||||
|
||||
actix = "0.13"
|
||||
actix-web = "4.4"
|
||||
actix-web-actors = "4.2"
|
||||
actix-cors = "0.7"
|
||||
|
||||
utoipa = "4.2"
|
||||
utoipa-swagger-ui = { version = "6.0", features = ["actix-web", "debug-embed"] }
|
||||
|
||||
log = "0.4"
|
||||
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.5", features = ["serde", "v4"] }
|
||||
itertools = "0.12"
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio", "macros", "chrono"] }
|
||||
|
||||
futures = "0.3"
|
||||
tokio = { version = "1.36", features = ["rt", "rt-multi-thread"] }
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
use std::process::{exit, Command};
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../api.v1.yaml");
|
||||
let output = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("yq . < ../api.v1.yaml > $OUT_DIR/api.v1.json")
|
||||
.output()
|
||||
.expect("Failed to convert api documentation to json");
|
||||
|
||||
if !output.status.success() {
|
||||
eprintln!("Error: {}", String::from_utf8_lossy(&output.stderr));
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue