document code

This commit is contained in:
alexisvisco 2019-03-26 10:25:49 +01:00
parent 0208b42e2a
commit 7f4cb89dca
5 changed files with 176 additions and 69 deletions

View file

@ -11,38 +11,41 @@ import (
)
var (
ClosedError = errors.New("sonic connection is closed")
InvalidChanName = errors.New("invalid channel name")
InvalidActionName = errors.New("invalid action name")
ClosedError = errors.New("sonic connection is closed")
InvalidChanName = errors.New("invalid channel name")
)
// Base contains commons commands to all channels.
type Base interface {
// Quit stop connection, you can't execute anything after calling this method.
// Syntax command QUIT
Quit() error
// Ping ping the sonic server.
// Return an error is there is something wrong.
// If an error occur, the sonic server is maybe down.
// Syntax command PING
Ping() error
}
type Driver struct {
Host string
Port int
Password string
Channel Channel
reader *bufio.Reader
conn net.Conn
closed bool
channel Channel
reader *bufio.Reader
conn net.Conn
closed bool
}
func NewControl(host string, port int, password string) (*Driver, error) {
driver := &Driver{
Host: host,
Port: port,
Password: password,
Channel: Ingest,
}
return driver, driver.connect()
}
func (c *Driver) connect() error {
if !IsChannelValid(c.Channel) {
// Connect open a connection via TCP with the sonic server.
func (c *Driver) Connect() error {
if !IsChannelValid(c.channel) {
return InvalidChanName
}
c.clean()
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, c.Port))
if err != nil {
return err
@ -50,7 +53,7 @@ func (c *Driver) connect() error {
c.conn = conn
c.reader = bufio.NewReader(c.conn)
err := c.write(fmt.Sprintf("START %s %s", c.Channel, c.Password))
err := c.write(fmt.Sprintf("START %s %s", c.channel, c.Password))
if err != nil {
return err
}
@ -64,6 +67,32 @@ func (c *Driver) connect() error {
}
}
func (c *Driver) Quit() error {
err := c.write("QUIT")
if err != nil {
return err
}
// should get ENDED
_, err = c.read()
c.clean()
return err
}
func (c Driver) Ping() error {
err := c.write("PING")
if err != nil {
return err
}
// should get PONG
_, err = c.read()
if err != nil {
return err
}
return nil
}
func (c *Driver) read() (string, error) {
if c.closed {
return "", ClosedError
@ -98,49 +127,6 @@ func (c Driver) write(str string) error {
return err
}
func (c *Driver) Quit() error {
err := c.write("QUIT")
if err != nil {
return err
}
// should get ENDED
_, err = c.read()
c.clean()
return err
}
func (c Driver) Ping() error {
err := c.write("PING")
if err != nil {
return err
}
// should get PONG
_, err = c.read()
if err != nil {
return err
}
return nil
}
func (c Driver) Trigger(action Action) error {
if IsActionValid(action) {
return InvalidActionName
}
err := c.write(fmt.Sprintf("TRIGGER %s", action))
if err != nil {
return err
}
// should get OK
_, err = c.read()
if err != nil {
return err
}
return nil
}
func (c *Driver) clean() {
c.closed = true
_ = c.conn.Close()