104 lines
2.2 KiB
Go
104 lines
2.2 KiB
Go
package entity
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"grpccanary/examples/grpcentity/protoapi"
|
|
"math/rand"
|
|
"net"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/reflection"
|
|
)
|
|
|
|
var min = 0
|
|
var max = 100
|
|
var port = ":8080"
|
|
|
|
func random(min, max int, src rand.Source) int {
|
|
return rand.New(src).Intn(max-min) + min
|
|
}
|
|
|
|
// Extra function for creating secure random numbers
|
|
//
|
|
// func randomSecure(min, max int) int {
|
|
// v, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
|
// if err != nil {
|
|
// fmt.Println(err)
|
|
// return min
|
|
// }
|
|
// fmt.Println("**", v, min, max)
|
|
|
|
// return min + int(v.Uint64())
|
|
// }
|
|
|
|
func getString(len int64, src rand.Source) string {
|
|
temp := ""
|
|
startChar := "!"
|
|
var i int64 = 1
|
|
for {
|
|
// For getting valid ASCII characters
|
|
myRand := random(0, 94, src)
|
|
newChar := string(startChar[0] + byte(myRand))
|
|
temp = temp + newChar
|
|
if i == len {
|
|
break
|
|
}
|
|
i++
|
|
}
|
|
return temp
|
|
}
|
|
|
|
type IoTServer struct {
|
|
protoapi.UnimplementedIoTServiceServer
|
|
}
|
|
|
|
func (IoTServer) GetDate(ctx context.Context, r *protoapi.RequestDateTime) (*protoapi.DateTime, error) {
|
|
currentTime := time.Now()
|
|
response := &protoapi.DateTime{
|
|
Value: currentTime.String(),
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func (IoTServer) UpdateSensingData(ctx context.Context, r *protoapi.SensingData) (*protoapi.SensingResponse, error) {
|
|
fmt.Printf("Received sensing data - Device: %s, Temp: %.2f°C, Humid: %.2f%%\n", r.GetDeviceId(), r.GetTemperature(), r.GetHumidity())
|
|
|
|
response := &protoapi.SensingResponse{
|
|
Success: true,
|
|
Message: fmt.Sprintf("Sensing data updated successfully for device %s", r.GetDeviceId()),
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func (IoTServer) GetRandomPass(ctx context.Context, r *protoapi.RequestPass) (*protoapi.RandomPass, error) {
|
|
src := rand.NewSource(r.GetSeed())
|
|
temp := getString(r.GetLength(), src)
|
|
|
|
response := &protoapi.RandomPass{
|
|
Password: temp,
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func ServerRun(addr string) {
|
|
server := grpc.NewServer()
|
|
var iotServer IoTServer
|
|
protoapi.RegisterIoTServiceServer(server, iotServer)
|
|
|
|
reflection.Register(server)
|
|
|
|
listen, err := net.Listen("tcp", port)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("Serving requests...")
|
|
server.Serve(listen)
|
|
}
|