/* Create by sndnvaps<sndnvaps@gmail.com>
* data: 2015-04-12
* upload 2 datapoint to yeelink.net at the same time
* post by sndnvaps
* hold on https://github.com/sndnvaps/MyRasPi
*/
//upload_client.go
import ( "fmt" "io/ioutil" "net" "time" "os" "strconv" ) func checkError(err error) { if err != nil { fmt.Fprintf(os.Stderr, "Fatal error: %s\n",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\n",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\n", tt/1000.00) return (tt/1000.00) } var c chan int func yeelink_upload(device_id, sensor_id string, val float32) { //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 \n") // fmt.Printf("Cpu temp = %2.2f\n", GetCpuTemp()) time.Sleep(time.Second) post := fmt.Sprintf("POST /v1.0/device/%s/sensor/%s/datapoints HTTP/1.0\r\nHost: api.yeelink.net\r\nAccept: */*\r\n",device_id,sensor_id); _ , err = conn.Write([]byte(post)); if err != nil { fmt.Printf("Sent Requset ok\n") }
fmt.Printf("Send the API-keys\n") time.Sleep(time.Second) // send the API-key _ , err = conn.Write([]byte("U-ApiKey: 108968b03a7e9334b2aca7c45bXXXXXX\r\nContent-Length: 15\r\nContent-type: application/json;charset=utf-8\r\n"))
//此处填写你自己的API-key checkError(err) time.Sleep(time.Second) //send the '\r\n' _ , err = conn.Write([]byte("\r\n")) checkError(err) //send the value time.Sleep(time.Second) var value string value = fmt.Sprintf("{\"value\":%2.2f}\n\n",val) //数据为 xx.xx //_ , err = conn.Write([]byte("{\"value\":13.14}\r\n")) _, err = conn.Write([]byte(value)) checkError(err) time.Sleep(time.Second) result, err := ioutil.ReadAll(conn) checkError(err) fmt.Println(string(result)) c <- 1 // os.Exit(1) } func main() { device_id := "XXXXX" //设备id sensor_id := "XXXXX" //传感器id sensor_id_2 := "XXXXX" //传感器id_2 val := GetCpuTemp() //此处的val只用于测试, 如果你有其它的参数,可以自行修改, val 类型为 float32, 长度需要5位,即xx.xx, 33.33 ,带2位小数 c = make(chan int) go yeelink_upload(device_id,sensor_id,val) // // time.Sleep(time.Second * 15) go yeelink_upload(device_id,sensor_id_2, val) //return <- c <- c }
实现同时上传二个Datapoint数据到yeelink.net
原理是使用golang chanel
运行效果如下图:
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)