[原创] linux 下上传 datapoint数据到yeelink 【golang版本】

package main

/* Create by sndnvaps<sndnvaps@gmail.com>
 * date : 2015-04-05 
 * upload datapoint to yeelink.net 
 * origin post by sndnvaps
 * hold on https://github.com/sndnvaps/MyRasPi 
 */

import (
   "fmt"
   "io/ioutil"
   "net"
   "time"
   "os"
   "strconv"
)


func checkError(err error) {
     if err != nil {
        fmt.Fprintf(os.Stderr, "Fatal error: %s
",err.Error())
        os.Exit(1)

        }
}

func GetCpuTemp() (t float32) {
      tf ,err := os.Open("/sys/class/thermal/thermal_zone0/temp")
      if err != nil {
      fmt.Printf("Read Cpu file error = %s
",err.Error())
      }
      defer tf.Close()
      data := make([]byte,5)
      tf.Read(data)
      data_temp := string(data)
      temp, _ := strconv.Atoi(data_temp)
      var tt float32
      tt = float32(temp)
      fmt.Printf("Cpu temp  = %2.2f
", tt/1000.00)

      return (tt/1000.00)


}




func main() {
        //Connet the api.yeelink.net
        //REMOTE_IP 42.96.164.52
        //PORT      80

        conn, err := net.Dial("tcp","42.96.164.52:80")
        defer conn.Close()
        checkError(err)
        fmt.Printf("Post Request 
")
//        fmt.Printf("Cpu temp = %2.2f
", GetCpuTemp())

        time.Sleep(time.Second)

    _  , err = conn.Write([]byte("POST /v1.0/device/19374/sensor/33945/datapoints HTTP/1.0
Host: api.yeelink.net
Accept: */*
"))      //此处要修改为你自己的设备号和传感器


    if err != nil {
           fmt.Printf("Sent Requset ok
")
        }
/*
    checkError(err)
    result, err := ioutil.ReadAll(conn)//get the info
    checkError(err)

  fmt.Println(string(result))
*/
        fmt.Printf("Send the API-keys
")
        time.Sleep(time.Second)

    // send the API-key
     _ , err = conn.Write([]byte("U-ApiKey: 108968b03a7e9334b2aca7c45b199dee
Content-Length: 15
Content-type: application/json;charset=utf-8
")) //请自行修改为自己的U-ApiKey  
checkError(err) time.Sleep(time.Second) //send the ' ' _ , err = conn.Write([]byte(" ")) checkError(err) //send the value time.Sleep(time.Second) var value string value = fmt.Sprintf("{"value":%2.2f} ",GetCpuTemp()) //_ , err = conn.Write([]byte("{"value":13.14} ")) // var b []byte //b = str2byte(value) // fmt.Println("b = ", b) _, err = conn.Write([]byte(value)) checkError(err) time.Sleep(time.Second) result, err := ioutil.ReadAll(conn) checkError(err) fmt.Println(string(result)) os.Exit(1) }

  可以直接使用go run upload_cpu_temp.go 

原文地址:https://www.cnblogs.com/sn-dnv-aps/p/4393961.html