Tanoda
NetworkSwitch.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Text;
4using Newtonsoft.Json;
5using UnityEngine;
7using UnityEngine.Networking;
8
9public class NetworkSwitch : MonoBehaviour
10{
11 public bool Polling = true;
12 public float PollingInterval = 0.5f;
13 public string ipAddress;
14 public UnityEvent On,Off;
15
16 void Start()
17 {
18 AddNewDevice((state) => {
19 if (state == "on")
20 On.Invoke();
21 else
22 Off.Invoke();
23 });
24 }
25
26 private void AddNewDevice(Action<string> state)
27 {
28 StartCoroutine(PollSonoff(state));
29 }
30
31 public void SwitchOn()
32 {
33 StartCoroutine(SonoffOn());
34 On.Invoke();
35 }
36 public void SwitchOff()
37 {
38 StartCoroutine(SonoffOff());
39 Off.Invoke();
40 }
41
42
43 private IEnumerator SonoffOff()
44 {
45 using (UnityWebRequest www = UnityWebRequest.Post(ipAddress + "/zeroconf/switch", ""))
46 {
47 www.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes("{\"data\":{\"switch\": \"off\"}}"));
48 www.SetRequestHeader("Content-Type", "text/plain");
49 yield return www.SendWebRequest();
50
51 if (www.isNetworkError || www.isHttpError)
52 {
53 Debug.LogError(www.error);
54 }
55 else
56 {
57 //ok
58 }
59 }
60 }
61
62 private IEnumerator SonoffOn()
63 {
64 using (UnityWebRequest www = UnityWebRequest.Post(ipAddress + "/zeroconf/switch", ""))
65 {
66 www.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes("{\"data\":{\"switch\": \"on\"}}"));
67 www.SetRequestHeader("Content-Type", "text/plain");
68 yield return www.SendWebRequest();
69
70 if (www.isNetworkError || www.isHttpError)
71 {
72 Debug.LogError(www.error);
73 }
74 else
75 {
76 //ok
77 }
78 }
79 }
80
81 private IEnumerator PollSonoff(Action<string> state)
82 {
83 while (Polling)
84 {
85 using (UnityWebRequest www = UnityWebRequest.Post(ipAddress + "/zeroconf/info", ""))
86 {
87 www.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes("{\"data\":{}}"));
88 www.SetRequestHeader("Content-Type", "text/plain");
89 yield return www.SendWebRequest();
90
91 if (www.isNetworkError || www.isHttpError)
92 {
93 Debug.LogError(www.error);
94 }
95 else
96 {
97 var info = JsonUtility.FromJson<SonoffInfo>(www.downloadHandler.text);
98 state(info.data.@switch);
99 }
100 }
101 yield return new WaitForSeconds(PollingInterval);
102 }
103 }
104
105 [Serializable]
106 private struct SonoffInfo
107 {
108 public int seq;
109 public int error;
110 public SonoffData data;
111 }
112 [Serializable]
113 private struct SonoffData
114 {
115 [JsonProperty("switch")]
116 public string @switch;
117 public string startup;
118 public string pulse;
119 public int pulseWidth;
120 public string ssid;
121 public string otaUnlock;
122 public string fwVersion;
123 public string deviceid;
124 public string bssid;
125 public int signalStrength;
126 }
127
128}
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
UnityEvent Off
string ipAddress
float PollingInterval
void SwitchOff()
UnityEvent On