Class: Iot::AnalysesController

Inherits:
BaseController show all
Defined in:
app/controllers/iot/analyses_controller.rb

Instance Method Summary collapse

Methods inherited from BaseController

#authenticate_thing!

Methods included from CallLoggable

#log_request, #log_response

Instance Method Details

#createObject


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
# File 'app/controllers/iot/analyses_controller.rb', line 21

def create
  report = params
  attributes = {}

  # Get sampled_at
  attributes[:sampled_at] = report.delete(:at).to_time if report[:at]

  # Get geolocation expected as WGS84
  if report[:latlon]
    attributes[:geolocation] = Charta.new_point(*report.delete(:latlon))
  end

  # Get indicators
  items = []
  report[:items] ||= {}
  report[:items].each do |name, value|
    indicator = Nomen::Indicator.find(name)
    unless indicator
      render json: { message: "Indicator #{name} is unacceptable" }, status: :not_acceptable
      return false
    end
    type = indicator.datatype.to_sym
    case type
    when :integer
      value = value.to_i
    when :decimal
      value = value.to_d
    when :boolean
      value = %w[yes true 1 ok].include?(value.downcase)
    when :choice
      unless indicator.choices.include?(value)
        render json: { message: "Indicator choice #{value} is unacceptable." }, status: :not_acceptable
        return false
      end
      value
    when :measure
      value = Measure.new(value)
    when :point
      value = Charta.new_point(*value)
    when :geometry
      value = Charta.new_geometry(value)
    end
    items << { indicator_name: name, value: value }
  end
  attributes[:items_attributes] = items
  attributes[:nature] = params[:type] || :sensor_analysis

  # Create analyses
  analysis = @sensor.analyses.create!(attributes)

  render json: { message: 'ok' }
end