Skip to content

Commit 554d502

Browse files
authored
配合 DeviceTalk 版本 (#2)
* update dan, dai. change cumstom format * Update README.rst
1 parent dfc7408 commit 554d502

File tree

6 files changed

+290
-266
lines changed

6 files changed

+290
-266
lines changed

README.rst

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,40 @@
11
ArduinoYun DA for IoTtalk v2
22
============================
3+
For iottalk v2 client, you have to install ``paho-mqtt``. Remember to install version 1.4.0: https://pypi.org/project/paho-mqtt/1.4.0/.
4+
5+
.. code-block::
6+
7+
wget https://files.pythonhosted.org/packages/25/63/db25e62979c2a716a74950c9ed658dce431b5cb01fde29eb6cba9489a904/paho-mqtt-1.4.0.tar.gz
8+
9+
pip install paho-mqtt-1.4.0.tar.gz
10+
311
412
To use this code, only ``custom.py`` needs to be modified.
513
This code uses device model ``MCU_board`` as an example, that is, the IDFs/ODFs are
614

715
.. code-block:: python
816
9-
def odf(): # int only
10-
11-
return [
12-
('D2', 0, 'D2'), #ODF_name, dimension, Variable_name in Bridge
13-
('D3', 0, 'D3'),
14-
('D4', 0, 'D4'),
15-
('D5~PWM', 0, 'D5~PWM'),
16-
('D6~PWM', 0, 'D6~PWM'),
17-
('D7', 0, 'D7'),
18-
('D8', 0, 'D8'),
19-
('D9~PWM', 0, 'D9~PWM'),
17+
def odf():
18+
return [ # ('odf_name', (param_strings in tuple))
19+
('D2-O', ('int', )),
20+
('D3-O', ('int', )),
21+
('D4-O', ('int', )),
22+
('D5Pwm-O', ('int', )),
23+
('D6Pwm-O', ('int', )),
24+
('D7-O', ('int', )),
25+
('D8-O', ('int', )),
26+
('D9Pwm-O', ('int', )),
2027
]
2128
2229
.. code-block:: python
2330
2431
def idf():
2532
26-
return [
27-
('A0', int), #IDF_name, Variable_type
28-
('A1', int),
29-
('A2', int),
30-
('A3', int),
31-
('A4', int),
32-
('A5', int),
33+
return [ # ('idf_name', (params in tuple))
34+
(('A0-I', ('int', )),
35+
('A1-I', ('int', )),
36+
('A2-I', ('int', )),
37+
('A3-I', ('int', )),
38+
('A4-I', ('int', )),
39+
('A5-I', ('int', )),
3340
]

custom.py

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,28 @@
1-
2-
3-
ServerIP = 'IoTtalk Ver. 2 Server IP'
4-
device_model ='MCU_board'
1+
api_url = 'IoTtalk Ver. 2 Server IP'
2+
device_model = 'MCU_board'
53
device_name = None
4+
# device_addr = 'your device addr'
65
username = None
7-
Comm_interval = 0.5 # unit:second
6+
push_interval = 0.5 # global interval
87

9-
def odf(): # int only
8+
def odf():
109
return [
11-
('D2', 0, 'D2'),
12-
('D3', 0, 'D3'),
13-
('D4', 0, 'D4'),
14-
('D5~PWM', 0, 'D5~PWM'),
15-
('D6~PWM', 0, 'D6~PWM'),
16-
('D7', 0, 'D7'),
17-
('D8', 0, 'D8'),
18-
('D9~PWM', 0, 'D9~PWM'),
10+
('D2-O', ('int', )),
11+
('D3-O', ('int', )),
12+
('D4-O', ('int', )),
13+
('D5Pwm-O', ('int', )),
14+
('D6Pwm-O', ('int', )),
15+
('D7-O', ('int', )),
16+
('D8-O', ('int', )),
17+
('D9Pwm-O', ('int', )),
1918
]
2019

2120
def idf():
2221
return [
23-
('A0', int),
24-
('A1', int),
25-
('A2', int),
26-
('A3', int),
27-
('A4', int),
28-
('A5', int),
29-
]
22+
('A0-I', ('int', )),
23+
('A1-I', ('int', )),
24+
('A2-I', ('int', )),
25+
('A3-I', ('int', )),
26+
('A4-I', ('int', )),
27+
('A5-I', ('int', )),
28+
]

dai.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
#!/usr/bin/env python3
2-
from multiprocessing import Process
2+
from multiprocessing import Process
33
import atexit
44
import importlib
55
import json
66
import re
77
import signal
88
import sys
99
import time
10-
import ida
10+
import sabridge
1111

1212
from threading import Thread
1313

@@ -20,6 +20,7 @@
2020

2121

2222
def push_data(df_name):
23+
2324
if not _devices[df_name].push_data:
2425
return
2526
while _flags[df_name]:
@@ -68,10 +69,6 @@ def main(app):
6869
if host is None:
6970
raise RegistrationError('host not given.')
7071

71-
port = app.__dict__.get('port')
72-
if port is None:
73-
port = 9992
74-
7572
from uuid import UUID
7673
device_addr = app.__dict__.get('device_addr')
7774
if device_addr:
@@ -141,7 +138,7 @@ def main(app):
141138

142139

143140
context = register(
144-
'http://{}:{}'.format(host, port),
141+
host,
145142
on_signal=on_signal,
146143
on_data=on_data,
147144
accept_protos=['mqtt'],
@@ -156,19 +153,18 @@ def main(app):
156153
)
157154

158155
atexit.register(deregister)
159-
160-
ida.Bridge2Arduino()
161-
162-
#signal.pause()
156+
157+
sabridge.Bridge2Arduino()
158+
159+
#signal.pause()
163160

164161
if __name__ == '__main__':
165162
if len(sys.argv) == 1:
166-
ida_filename = 'ida'
163+
sabridge_filename = 'sabridge'
167164
elif len(sys.argv) == 2:
168-
ida_filename = sys.argv[1]
169-
app = importlib.import_module(ida_filename)
170-
165+
sabridge_filename = sys.argv[1]
166+
app = importlib.import_module(sabridge_filename)
171167
main(app)
172-
173-
174-
168+
169+
170+

dan.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -318,23 +318,23 @@ def register(self, url, on_signal, on_data,
318318
if profile:
319319
body['profile'] = profile
320320

321-
try:
322-
response = requests.put(
321+
print(self.context.url)
322+
response = requests.put(
323323
'{}/{}'.format(self.context.url, self.context.app_id),
324324
headers={
325325
'Content-Type': 'application/json',
326326
},
327-
data=json.dumps(body)
327+
data=json.dumps(body), verify=False
328328
)
329329

330-
if response.status_code != 200:
330+
if response.status_code != 200:
331331
raise RegistrationError(response.json()['reason'])
332-
else:
332+
else:
333333
print('device id = ', response.json()['id'])
334334
print('device name = ', response.json()['name'])
335335

336-
except requests.exceptions.ConnectionError:
337-
raise RegistrationError('ConnectionError')
336+
#except requests.exceptions.ConnectionError:
337+
# raise RegistrationError('ConnectionError')
338338

339339
metadata = response.json()
340340
self.context.mqtt_host = metadata['url']['host']

ida.py renamed to sabridge.py

Lines changed: 62 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from uuid import getnode
33
import time, sys, os, Queue
44
from dan import NoData
5+
import struct
56
import custom
67

78
sys.path.insert(0, '/usr/lib/python2.7/bridge/')
@@ -11,36 +12,36 @@
1112
odfInfo = custom.odf()
1213
ODFcache = {}
1314
IDFcache = {}
15+
1416
IDFsignal = {}
1517
odf2Bridge = {}
18+
1619
incomming = {}
1720
for f_name in [t[0] for t in odfInfo]:
1821
incomming[f_name] = 0
1922
timestamp = time.time()
2023

24+
odfMap = {
25+
odf[0]: odf[1]
26+
for odf in odfInfo
27+
}
2128

2229
os.system(r'echo "none" > /sys/class/leds/ds:green:usb/trigger')
2330
os.system(r'echo "none" > /sys/class/leds/ds:green:wlan/trigger')
2431

2532

2633
class app(dict):
27-
global ODFcache, IDFcache, odf2Bridge
34+
global ODFcache, IDFcache, odf2Bridge, odfMap
2835

29-
host = custom.ServerIP
36+
host = custom.api_url
3037
device_name = custom.device_name
3138
device_model = custom.device_model
32-
device_addr = "{:012X}".format(getnode())
39+
device_addr = custom.device_addr
3340
username = custom.username # optional
34-
push_interval = custom.Comm_interval # global interval
41+
push_interval = custom.push_interval # global interval
3542

3643
idf_list = [t[0] for t in idfInfo]
37-
odf_list = []
38-
for t in odfInfo:
39-
if t[0] not in odf_list:
40-
odf_list.append(t[0])
41-
odf2Bridge[t[0]] = [[t[1], t[2]]]
42-
else:
43-
odf2Bridge[t[0]].append([t[1], t[2]])
44+
odf_list = [t[0] for t in odfInfo]
4445

4546
def __init__(self):
4647

@@ -86,6 +87,7 @@ def forIDF(idf_name):
8687

8788
@staticmethod
8889
def forODF(odf_name, data):
90+
print(odf_name, data)
8991
os.system(r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger')
9092
global ODFcache
9193

@@ -97,10 +99,36 @@ def forODF(odf_name, data):
9799

98100
os.system(r'echo "none" > /sys/class/leds/ds:green:wlan/trigger')
99101

102+
def odfdata_to_string(data, params):
103+
r = ''
104+
for i in range(len(data)):
105+
if params[i] == 'int':
106+
r += ',%9d' % int(data[i])
107+
elif params[i] == 'float':
108+
r += ',%9f' % float(data[i])
109+
else:
110+
r += ',%9d' % 0
111+
return r[1:]
112+
113+
def string_to_idfdata(data_list, params):
114+
if len(data_list) != len(params):
115+
return None
116+
r = []
117+
for i in range(len(params)):
118+
try:
119+
if params[i] == 'int':
120+
r.append(int(data_list[i]))
121+
elif params[i] == 'float':
122+
r.append(float(data_list[i]))
123+
else:
124+
return None
125+
except:
126+
return None
127+
return r
100128

101129
BClient = BridgeClient()
102130
def Bridge2Arduino():
103-
global incomming, ODFcache, IDFcache, timestamp, IDFsignal
131+
global incomming, ODFcache, IDFcache, timestamp, IDFsignal, odfMap
104132

105133
while True:
106134
for ODF in ODFcache:
@@ -110,44 +138,38 @@ def Bridge2Arduino():
110138
if data == None:
111139
continue
112140

113-
for dimension in odf2Bridge[ODF]:
114-
if data[dimension[0]] is None:
115-
continue
116-
117-
BClient.put(dimension[1], str(int(data[dimension[0]])))
118-
119-
'''
120-
print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format(
121-
f=ODF,
122-
d=dimension[0],
123-
p=dimension[1],
124-
v=str(int(data[dimension[0]])),
125-
i=incomming[ODF],)
126-
'''
127-
128-
incomming[ODF] = incomming[ODF] ^ 1
129-
BClient.put('incomming_'+ODF, str(incomming[ODF]))
141+
if len(data) != len(odfMap[ODF]):
142+
print('ODF: %s, get data which wrong dimension' % ODF)
143+
BClient.put(ODF, odfdata_to_string(data, odfMap[ODF]))
144+
incomming[ODF] = incomming[ODF] ^ 1
145+
BClient.put('incomming_'+ODF, str(incomming[ODF]))
146+
print('BClient.put [%s]: %s. Incomming: %s' % (ODF, odfdata_to_string(data, odfMap[ODF]), str(incomming[ODF])))
147+
continue
148+
130149
else:
131150
pass
132151

133-
if time.time() - timestamp >= app.push_interval:
152+
if time.time() - timestamp >= app.push_interval*0.5:
134153
for IDF in idfInfo:
135-
if IDFsignal.get(IDF[0]):
136-
tmp = BClient.get(IDF[0])
137-
IDFsignal[IDF[0]] = 0
154+
idfName = IDF[0]
155+
idfParams = IDF[1]
156+
if IDFsignal.get(idfName):
157+
getValue = BClient.get(idfName)
158+
IDFsignal[idfName] = 0
138159
else:
139-
tmp = None
160+
getValue = None
140161

141-
if tmp is None:
162+
if getValue is None:
142163
pass
143164
else:
144-
v = IDF[1](tmp)
165+
v = string_to_idfdata(getValue.split(','), idfParams)
145166
if v is not None:
146-
if IDFcache[IDF[0]].qsize():
147-
IDFcache[IDF[0]].get()
148-
IDFcache[IDF[0]].put(v)
167+
print('BClient.get [%s]: %s.' % (idfName, v))
168+
if IDFcache[idfName].qsize():
169+
IDFcache[idfName].get()
170+
IDFcache[idfName].put(v)
149171
else:
150-
IDFcache[IDF[0]].put(v)
172+
IDFcache[idfName].put(v)
151173
timestamp = time.time()
152174

153175

0 commit comments

Comments
 (0)