-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol_system.cr
More file actions
489 lines (405 loc) · 15 KB
/
control_system.cr
File metadata and controls
489 lines (405 loc) · 15 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
require "time"
require "uri"
require "future"
require "./converter/time_location"
require "./base/model"
require "./settings"
require "./email"
require "./utilities/settings_helper"
require "./utilities/metadata_helper"
require "./playlist"
module PlaceOS::Model
class ControlSystem < ModelBase
include PlaceOS::Model::Timestamps
include Utilities::SettingsHelper
include Utilities::MetadataHelper
include Playlist::Checker
table :sys
attribute name : String, es_subfield: "keyword"
attribute description : String = ""
# Room search meta-data
# Building + Level are both filtered using zones
attribute features : Set(String) = -> { Set(String).new }
attribute email : Email?, converter: PlaceOS::Model::EmailConverter
attribute bookable : Bool = false
attribute public : Bool = false
attribute display_name : String?
attribute code : String?
attribute type : String?
attribute capacity : Int32 = 0
attribute map_id : String?
attribute approval : Bool = false
# Array of URLs to images for a system
attribute images : Array(String) = -> { [] of String }
# Array of security group ids for room access
attribute security_groups : Array(String) = -> { [] of String }
attribute timezone : Time::Location?, converter: Time::Location::Converter, es_type: "text"
# Provide fields for simplifying support
attribute support_url : String = ""
attribute timetable_url : String? # The timetable visualisation
attribute camera_snapshot_url : String? # snapshot images of the room
attribute camera_snapshot_urls : Array(String) = -> { [] of String }
attribute camera_url : String? # admin control
# if not bookable via google / O365 calendaring systems
attribute room_booking_url : String?
attribute version : Int32 = 0
# The number of UI devices that are always available in the room
# i.e. the number of iPads mounted on the wall
attribute installed_ui_devices : Int32 = 0
# IDs of associated models
attribute zones : Array(String) = [] of String, es_type: "keyword"
attribute modules : Array(String) = [] of String, es_type: "keyword"
# Systems as digital signage displays
# playlists can be assigned directly to displays or to zones
# playlists in zones will only be loaded if they have matching orientations
attribute orientation : Playlist::Orientation = Playlist::Orientation::Unspecified, converter: PlaceOS::Model::PGEnumConverter(PlaceOS::Model::Playlist::Orientation)
attribute playlists : Array(String) = [] of String, es_type: "keyword"
attribute signage : Bool = false
# Associations
###############################################################################################
# Encrypted yaml settings, with metadata
has_many(
child_class: Settings,
collection_name: "settings_and_versions",
foreign_key: "parent_id",
dependent: :destroy
)
# Metadata belonging to this control_system
has_many(
child_class: Metadata,
collection_name: "metadata_and_versions",
foreign_key: "parent_id",
dependent: :destroy
)
# Single System triggers
has_many(
child_class: Trigger,
dependent: :destroy,
collection_name: :system_triggers,
foreign_key: "control_system_id"
)
# Validation
###############################################################################################
# Zones and settings are only required for confident coding
validates :name, presence: true
# TODO: Ensure unique regardless of casing
ensure_unique :name do |name|
name.strip
end
# Validate support URI
validate ->(this : ControlSystem) {
if url = this.camera_snapshot_url
this.validation_error(:camera_snapshot_url, "is an invalid URI") unless Validation.valid_uri?(url)
end
this.camera_snapshot_urls.each do |url|
if !Validation.valid_uri?(url)
this.validation_error(:camera_snapshot_urls, "contains an invalid URI")
break
end
end
return if this.support_url.blank?
this.validation_error(:support_url, "is an invalid URI") unless Validation.valid_uri?(this.support_url)
}
before_save :unique_camera_urls
def unique_camera_urls
update_camera_urls
unique_urls = self.camera_snapshot_urls.uniq
if unique_urls.size != self.camera_snapshot_urls.size
self.camera_snapshot_urls = unique_urls
end
end
def update_camera_urls
url = camera_snapshot_url
if camera_snapshot_urls.size == 1 && url && !@camera_snapshot_urls_changed && @camera_snapshot_url_changed
self.camera_snapshot_urls[0] = url
@camera_snapshot_urls_changed = true
elsif url && camera_snapshot_urls.empty?
camera_snapshot_urls.insert(0, url)
@camera_snapshot_urls_changed = true
end
self.camera_snapshot_url = camera_snapshot_urls.first?
end
def camera_snapshot_urls=(vals : Array(String))
@camera_snapshot_urls = vals
@camera_snapshot_urls_changed = true
vals
end
# Queries
###############################################################################################
def self.by_zone_id(id)
ControlSystem.where("$1 = Any(zones)", id)
end
@[Deprecated("Use `by_zone_id`")]
def self.in_zone(id)
self.by_zone_id(id)
end
def self.by_module_id(id)
ControlSystem.where("$1 = Any(modules)", id)
end
@[Deprecated("Use `by_module_id`")]
def self.using_module(id)
self.by_module_id(id)
end
# Obtains the control system's modules as json
# FIXME: Dreadfully needs optimisation, i.e. subset serialisation
def module_data
Module.find_all(self.modules).to_a.map do |mod|
# Pick off driver name, and module_name from associated driver
driver_data = mod.driver.try do |driver|
{
:driver => {
name: driver.name,
module_name: driver.module_name,
},
}
end
if driver_data
JSON.parse(mod.to_json).as_h.merge(driver_data).to_json
else
mod.to_json
end
end
end
# Obtains the control system's zones as json
def zone_data
Zone.find_all(self.zones).to_a.map(&.to_json)
end
# Triggers
def triggers
TriggerInstance.for(self.id)
end
# Collect Settings ordered by hierarchy
#
# Control System < Zone/n < Zone/(n-1) < ... < Zone/0
def settings_hierarchy : Array(Settings)
# Start with Control System Settings
hierarchy = settings
# Zone Settings
zone_models = Model::Zone.find_all(self.zones).to_a
# Merge by highest associated zone
self.zones.reverse_each do |zone_id|
next if (zone = zone_models.find &.id.==(zone_id)).nil?
begin
hierarchy.concat(zone.settings)
rescue error
Log.warn(exception: error) { "failed to merge zone #{zone_id} settings" }
end
end
hierarchy.compact
end
# Callbacks
###############################################################################################
before_destroy :cleanup_modules
before_save :check_zones
before_save :check_modules
after_save :update_triggers
# Internal modules
private IGNORED_MODULES = ["__Triggers__"]
# Remove Modules not associated with any other systems
# NOTE: Includes compulsory associated Logic Modules
def cleanup_modules
return if self.modules.empty?
modules_with_single_occurrence.map do |m|
future { m.destroy }
end.each(&.get)
end
def modules_with_single_occurrence : Array(Module)
Module.where(%[
id IN (
SELECT module
FROM (
SELECT UNNEST(modules) AS module
FROM sys
) AS module_list
WHERE module IN ('#{self.modules.join("', '")}')
GROUP BY module
HAVING COUNT(*) = 1)
]).to_a
end
# ensure all the modules are valid and exist
def check_modules
sql_query = %[
WITH input_ids AS (
SELECT unnest(#{Associations.format_list_for_postgres(self.modules)}) AS id
)
SELECT ARRAY_AGG(input_ids.id)
FROM input_ids
LEFT JOIN mod ON input_ids.id = mod.id
WHERE mod.id IS NULL;
]
remove_mods = ::PgORM::Database.connection do |conn|
conn.query_one(sql_query, &.read(Array(String)?))
end
if remove_mods && !remove_mods.empty?
self.modules = self.modules - remove_mods
end
end
private getter remove_zones : Array(String) { [] of String }
private getter add_zones : Array(String) { [] of String }
private property? update_triggers = false
# Update the zones on the model
protected def check_zones
if self.zones_changed?
previous = self.zones_was || [] of String
current = self.zones
@remove_zones = previous - current
@add_zones = current - previous
self.update_triggers = !remove_zones.empty? || !add_zones.empty?
else
self.update_triggers = false
end
end
# Updates triggers after save
#
# - Destroy `Trigger`s from removed zones
# - Adds `TriggerInstance`s to added zones
protected def update_triggers
return unless update_triggers?
unless remove_zones.empty?
trigger_models = self.triggers.to_a
# Remove ControlSystem's triggers associated with the removed zone
Zone.find_all(remove_zones).each do |zone|
# Destroy the associated triggers
zone.triggers.each do |trig_id|
trigger_models.each do |trigger_model|
# Ensure trigger is for the removed zone
if trigger_model.trigger_id == trig_id && trigger_model.zone_id == zone.id
trigger_model.destroy
end
end
end
end
end
# Add trigger instances to zones
Zone.find_all(add_zones).each do |zone|
zone.triggers.each do |trig_id|
inst = TriggerInstance.new(trigger_id: trig_id, zone_id: zone.id)
inst.control_system = self
inst.save
end
end
end
# Module Management
###############################################################################################
# Removes the module from the system and deletes it if not used elsewhere
#
def add_module(module_id : String)
if !self.modules.includes?(module_id) && ControlSystem.add_module(id.as(String), module_id)
self.modules << module_id
self.version = ControlSystem.find(id).version
end
end
def self.add_module(control_system_id : String, module_id : String)
response = ::PgORM::Database.connection do |db|
db.exec(<<-SQL, control_system_id, [module_id])
update #{ControlSystem.table_name} set modules = modules || $2, version = version + 1 where id = $1
SQL
end
response.rows_affected > 0
end
# Removes the module from the system and deletes it if not used elsewhere
#
def remove_module(module_id : String)
mod = Module.find?(module_id)
if self.modules.includes?(module_id) && ControlSystem.remove_module(id.as(String), module_id)
self.modules_will_change!
self.modules.delete(module_id)
unless mod.nil?
# Remove the module from the control system's features
self.features_will_change!
self.features.delete(mod.resolved_name)
self.features.delete(mod.name)
end
self.version = ControlSystem.find(id).version
end
end
def self.remove_module(control_system_id : String, module_id : String)
response = ::PgORM::Database.connection do |db|
db.exec(<<-SQL, control_system_id, [module_id])
update #{ControlSystem.table_name} set modules=(select array(select unnest(modules) except select unnest($2::text[]))), version = version + 1 where id = $1
SQL
end
return false unless response.rows_affected > 0
# Keep if any other ControlSystem is using the module
still_in_use = ControlSystem.by_module_id(module_id).any? do |sys|
sys.id != control_system_id
end
Module.find?(module_id).try(&.destroy) unless still_in_use
Log.debug { {
message: "module removed from system #{still_in_use ? "still in use" : "deleted as not in any other systems"}",
module_id: module_id,
control_system_id: control_system_id,
} }
true
end
# Playlist management
# ===================
def playlists_last_updated(playlists : Hash(String, Array(String)) = all_playlists) : Time
playlist_ids = playlists.values.flatten.uniq!
if !playlist_ids.empty?
play_updated_at = Playlist.where(id: playlist_ids).order(updated_at: :desc).limit(1).to_a.first?.try(&.updated_at)
rev_updated_at = Playlist::Revision.where(playlist_id: playlist_ids, approved: true).order(updated_at: :desc).limit(1).to_a.first?.try(&.updated_at)
end
trig_updated_at = TriggerInstance
.where(control_system_id: self.id.as(String))
.where("cardinality(playlists) > ?", 0)
.order(updated_at: :desc)
.limit(1).to_a.first?.try(&.updated_at)
[play_updated_at, rev_updated_at, trig_updated_at, self.updated_at].compact.max
end
def self.with_playlists(ids : Enumerable(String))
ControlSystem.where("playlists @> #{Associations.format_list_for_postgres(ids)}")
end
def all_playlists : Hash(String, Array(String))
# find all the zones and triggers with playlists configured
# then construct a hash
sys_id = self.id.as(String)
sql_query = %[
WITH settings AS (
SELECT
zones,
orientation
FROM sys
WHERE id = $1
),
all_playlists AS (
-- unnest() in the SELECT is implicitly lateral
SELECT
z.id AS source_id,
unnest(z.playlists) AS playlist_id
FROM zone z
JOIN settings st
ON z.id = ANY(st.zones)
UNION ALL
SELECT
t.id,
unnest(t.playlists)
FROM trig t
WHERE t.control_system_id = $1
)
SELECT
ap.source_id,
array_agg(ap.playlist_id ORDER BY ap.playlist_id) AS playlists
FROM all_playlists ap
JOIN settings st ON TRUE
JOIN playlists p ON p.id = ap.playlist_id
WHERE
st.orientation = 'UNSPECIFIED'
OR p.orientation = st.orientation
OR p.orientation = 'UNSPECIFIED'
GROUP BY ap.source_id;
]
playlists = {
sys_id => self.playlists,
}
::PgORM::Database.connection do |conn|
conn.query(sql_query, args: [sys_id]) do |rs|
while rs.move_next
playlists[rs.read(String)] = rs.read(Array(String))
end
end
end
playlists
end
end
end