# CozyLife WiFi LED strip
# code derived from https://github.com/cozylife/hass_cozylife_local_pull/blob/master/custom_components/hass_cozylife_local_pull/tcp_client.py#L134

import socket, time, json, sys
TCP_IP = '192.168.178.81'
TCP_PORT = 5555
BUFFER_SIZE = 1024

if str(sys.argv[1]) == 'off':
  payload = {'1': 0}
else:
  payload = {'1': 255, '2': 0}
  
  # brightness 1 - 1000 (CozyLife nutzt nur 1-400)
  payload['4'] = int(sys.argv[1])
  
  # hs_color https://www.home-assistant.io/integrations/light/#service-lightturn_on
  payload['5'] = int(sys.argv[2])
  payload['6'] = int(sys.argv[3]) * 10
  
  # weiß 0 0 
  # rot 0 100
  # grün 120 100
  # blau 240 100
  # gelb 60 100
  # orange 24 100
  
  # colortemp
  #payload['3'] = 900

message = {
  'pv': 0,
  'cmd': 3,
  'sn': str(int(round(time.time() * 1000))),
  'msg': {
    'attr': [int(item) for item in payload.keys()],
    'data': payload,
  }
}

payload_str = json.dumps(message, separators=(',', ':',))
message_bytes = bytes(payload_str + "\r\n", encoding='utf8')

#MESSAGE = '{"pv":0,"cmd":2,"sn":"' + str(int(round(time.time() * 1000))) + '","msg":{"attr":[0]}}' + "\r\n"
#print MESSAGE
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(message_bytes)
data = s.recv(BUFFER_SIZE)
s.close()
print(data)