toit

How can I store a weather station data into a Toit metric?


I have successfully followed the tutorial to build the weather station. However, I now want to store the collected data in a metric subscription. Aside the fact that I am failing to create a subscription, assuming I have a temperature metric subscription, how could I store the data there?

In other words, I want to store the $bme.read_temperature into the temperature metric so that I can then read it with toit data read metrics temperature

Thanks in advance,


Solution

  • The best way to do this is using pubsub. To publish the temperature to a pubsub topic do:

    import pubsub
    import encoding.json
    import gpio
    import i2c
    import drivers.bme280 as drivers
    
    main:
      bus := i2c.Bus
        --sda=gpio.Pin 21
        --scl=gpio.Pin 22
    
      device := bus.device drivers.I2C_ADDRESS_ALT
    
      bme := drivers.Bme280 device
    
      bme.on
    
      tmp := bme.read_temperature
      pubsub.publish "cloud:temperature" 
        json.encode {"t": tmp}
    

    To read the data using the CLI, first you have to create a subscription:

    toit pubsub subscription create cloud:temperature my-temp-sub
    

    next, run the application code and try and read the temperature from the CLI using:

    toit pubsub read cloud:temperature my-temp-sub
    

    To get more information on pubsub checkout https://docs.toit.io/platform/tutorials/pubsub/pubsubext