package micadc

import (
	"bytes"
	"encoding/binary"
	"netease_control_center/nembd/base"
	"os"
	"syscall"
)

/*
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stddef.h>
*/
import "C"

const (
	devpath   = "/dev/i2c_operator_device"
	MAGIC_NUM = 'A'
	CMD_SET   = 0
	CMD_GET   = 1
)

func MicAdcSet(adcnum int, reg_addr int, reg_val int) error {
	fd, err := os.Open(devpath)
	if err != nil {
		return err
	}
	defer fd.Close()

	buf := I2c_ioctl_msg(int32(adcnum), int32(reg_addr), int32(reg_val))
	cmd := base.IOW(MAGIC_NUM, CMD_SET, uint32(len(buf)))

	tmp := C.CBytes(buf)
	//fmt.Println("arg:", adcnum, reg_addr, reg_val)
	//fmt.Println("buf:", len(buf), buf)

	_, _, err2 := syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), uintptr(cmd), uintptr(tmp))

	C.free(tmp)

	if err2 != 0 {
		return syscall.Errno(err2)
	}

	return nil
}
func I2c_ioctl_msg(i2c_index int32, reg_addr int32, reg_val int32) []byte {
	buf := new(bytes.Buffer)
	binary.Write(buf, binary.LittleEndian, int32(i2c_index))
	binary.Write(buf, binary.LittleEndian, int32(reg_addr))
	binary.Write(buf, binary.LittleEndian, int32(reg_val))
	return buf.Bytes()
}
