Skip to content

Commit

Permalink
配合 DeviceTalk 版本 (#2)
Browse files Browse the repository at this point in the history
* update dan, dai. change cumstom format

* Update README.rst
  • Loading branch information
EricPwg authored Nov 9, 2022
1 parent dfc7408 commit 554d502
Show file tree
Hide file tree
Showing 6 changed files with 290 additions and 266 deletions.
43 changes: 25 additions & 18 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,33 +1,40 @@
ArduinoYun DA for IoTtalk v2
============================
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/.

.. code-block::
wget https://files.pythonhosted.org/packages/25/63/db25e62979c2a716a74950c9ed658dce431b5cb01fde29eb6cba9489a904/paho-mqtt-1.4.0.tar.gz
pip install paho-mqtt-1.4.0.tar.gz
To use this code, only ``custom.py`` needs to be modified.
This code uses device model ``MCU_board`` as an example, that is, the IDFs/ODFs are

.. code-block:: python
def odf(): # int only
return [
('D2', 0, 'D2'), #ODF_name, dimension, Variable_name in Bridge
('D3', 0, 'D3'),
('D4', 0, 'D4'),
('D5~PWM', 0, 'D5~PWM'),
('D6~PWM', 0, 'D6~PWM'),
('D7', 0, 'D7'),
('D8', 0, 'D8'),
('D9~PWM', 0, 'D9~PWM'),
def odf():
return [ # ('odf_name', (param_strings in tuple))
('D2-O', ('int', )),
('D3-O', ('int', )),
('D4-O', ('int', )),
('D5Pwm-O', ('int', )),
('D6Pwm-O', ('int', )),
('D7-O', ('int', )),
('D8-O', ('int', )),
('D9Pwm-O', ('int', )),
]
.. code-block:: python
def idf():
return [
('A0', int), #IDF_name, Variable_type
('A1', int),
('A2', int),
('A3', int),
('A4', int),
('A5', int),
return [ # ('idf_name', (params in tuple))
(('A0-I', ('int', )),
('A1-I', ('int', )),
('A2-I', ('int', )),
('A3-I', ('int', )),
('A4-I', ('int', )),
('A5-I', ('int', )),
]
41 changes: 20 additions & 21 deletions custom.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@


ServerIP = 'IoTtalk Ver. 2 Server IP'
device_model ='MCU_board'
api_url = 'IoTtalk Ver. 2 Server IP'
device_model = 'MCU_board'
device_name = None
# device_addr = 'your device addr'
username = None
Comm_interval = 0.5 # unit:second
push_interval = 0.5 # global interval

def odf(): # int only
def odf():
return [
('D2', 0, 'D2'),
('D3', 0, 'D3'),
('D4', 0, 'D4'),
('D5~PWM', 0, 'D5~PWM'),
('D6~PWM', 0, 'D6~PWM'),
('D7', 0, 'D7'),
('D8', 0, 'D8'),
('D9~PWM', 0, 'D9~PWM'),
('D2-O', ('int', )),
('D3-O', ('int', )),
('D4-O', ('int', )),
('D5Pwm-O', ('int', )),
('D6Pwm-O', ('int', )),
('D7-O', ('int', )),
('D8-O', ('int', )),
('D9Pwm-O', ('int', )),
]

def idf():
return [
('A0', int),
('A1', int),
('A2', int),
('A3', int),
('A4', int),
('A5', int),
]
('A0-I', ('int', )),
('A1-I', ('int', )),
('A2-I', ('int', )),
('A3-I', ('int', )),
('A4-I', ('int', )),
('A5-I', ('int', )),
]
32 changes: 14 additions & 18 deletions dai.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#!/usr/bin/env python3
from multiprocessing import Process
from multiprocessing import Process
import atexit
import importlib
import json
import re
import signal
import sys
import time
import ida
import sabridge

from threading import Thread

Expand All @@ -20,6 +20,7 @@


def push_data(df_name):

if not _devices[df_name].push_data:
return
while _flags[df_name]:
Expand Down Expand Up @@ -68,10 +69,6 @@ def main(app):
if host is None:
raise RegistrationError('host not given.')

port = app.__dict__.get('port')
if port is None:
port = 9992

from uuid import UUID
device_addr = app.__dict__.get('device_addr')
if device_addr:
Expand Down Expand Up @@ -141,7 +138,7 @@ def main(app):


context = register(
'http://{}:{}'.format(host, port),
host,
on_signal=on_signal,
on_data=on_data,
accept_protos=['mqtt'],
Expand All @@ -156,19 +153,18 @@ def main(app):
)

atexit.register(deregister)

ida.Bridge2Arduino()

#signal.pause()

sabridge.Bridge2Arduino()

#signal.pause()

if __name__ == '__main__':
if len(sys.argv) == 1:
ida_filename = 'ida'
sabridge_filename = 'sabridge'
elif len(sys.argv) == 2:
ida_filename = sys.argv[1]
app = importlib.import_module(ida_filename)

sabridge_filename = sys.argv[1]
app = importlib.import_module(sabridge_filename)
main(app)






14 changes: 7 additions & 7 deletions dan.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,23 +318,23 @@ def register(self, url, on_signal, on_data,
if profile:
body['profile'] = profile

try:
response = requests.put(
print(self.context.url)
response = requests.put(
'{}/{}'.format(self.context.url, self.context.app_id),
headers={
'Content-Type': 'application/json',
},
data=json.dumps(body)
data=json.dumps(body), verify=False
)

if response.status_code != 200:
if response.status_code != 200:
raise RegistrationError(response.json()['reason'])
else:
else:
print('device id = ', response.json()['id'])
print('device name = ', response.json()['name'])

except requests.exceptions.ConnectionError:
raise RegistrationError('ConnectionError')
#except requests.exceptions.ConnectionError:
# raise RegistrationError('ConnectionError')

metadata = response.json()
self.context.mqtt_host = metadata['url']['host']
Expand Down
102 changes: 62 additions & 40 deletions ida.py → sabridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from uuid import getnode
import time, sys, os, Queue
from dan import NoData
import struct
import custom

sys.path.insert(0, '/usr/lib/python2.7/bridge/')
Expand All @@ -11,36 +12,36 @@
odfInfo = custom.odf()
ODFcache = {}
IDFcache = {}

IDFsignal = {}
odf2Bridge = {}

incomming = {}
for f_name in [t[0] for t in odfInfo]:
incomming[f_name] = 0
timestamp = time.time()

odfMap = {
odf[0]: odf[1]
for odf in odfInfo
}

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


class app(dict):
global ODFcache, IDFcache, odf2Bridge
global ODFcache, IDFcache, odf2Bridge, odfMap

host = custom.ServerIP
host = custom.api_url
device_name = custom.device_name
device_model = custom.device_model
device_addr = "{:012X}".format(getnode())
device_addr = custom.device_addr
username = custom.username # optional
push_interval = custom.Comm_interval # global interval
push_interval = custom.push_interval # global interval

idf_list = [t[0] for t in idfInfo]
odf_list = []
for t in odfInfo:
if t[0] not in odf_list:
odf_list.append(t[0])
odf2Bridge[t[0]] = [[t[1], t[2]]]
else:
odf2Bridge[t[0]].append([t[1], t[2]])
odf_list = [t[0] for t in odfInfo]

def __init__(self):

Expand Down Expand Up @@ -86,6 +87,7 @@ def forIDF(idf_name):

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

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

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

def odfdata_to_string(data, params):
r = ''
for i in range(len(data)):
if params[i] == 'int':
r += ',%9d' % int(data[i])
elif params[i] == 'float':
r += ',%9f' % float(data[i])
else:
r += ',%9d' % 0
return r[1:]

def string_to_idfdata(data_list, params):
if len(data_list) != len(params):
return None
r = []
for i in range(len(params)):
try:
if params[i] == 'int':
r.append(int(data_list[i]))
elif params[i] == 'float':
r.append(float(data_list[i]))
else:
return None
except:
return None
return r

BClient = BridgeClient()
def Bridge2Arduino():
global incomming, ODFcache, IDFcache, timestamp, IDFsignal
global incomming, ODFcache, IDFcache, timestamp, IDFsignal, odfMap

while True:
for ODF in ODFcache:
Expand All @@ -110,44 +138,38 @@ def Bridge2Arduino():
if data == None:
continue

for dimension in odf2Bridge[ODF]:
if data[dimension[0]] is None:
continue

BClient.put(dimension[1], str(int(data[dimension[0]])))

'''
print '{f}[{d}] -> {p} = {v}, incomming[{f}] = {i}'.format(
f=ODF,
d=dimension[0],
p=dimension[1],
v=str(int(data[dimension[0]])),
i=incomming[ODF],)
'''

incomming[ODF] = incomming[ODF] ^ 1
BClient.put('incomming_'+ODF, str(incomming[ODF]))
if len(data) != len(odfMap[ODF]):
print('ODF: %s, get data which wrong dimension' % ODF)
BClient.put(ODF, odfdata_to_string(data, odfMap[ODF]))
incomming[ODF] = incomming[ODF] ^ 1
BClient.put('incomming_'+ODF, str(incomming[ODF]))
print('BClient.put [%s]: %s. Incomming: %s' % (ODF, odfdata_to_string(data, odfMap[ODF]), str(incomming[ODF])))
continue

else:
pass

if time.time() - timestamp >= app.push_interval:
if time.time() - timestamp >= app.push_interval*0.5:
for IDF in idfInfo:
if IDFsignal.get(IDF[0]):
tmp = BClient.get(IDF[0])
IDFsignal[IDF[0]] = 0
idfName = IDF[0]
idfParams = IDF[1]
if IDFsignal.get(idfName):
getValue = BClient.get(idfName)
IDFsignal[idfName] = 0
else:
tmp = None
getValue = None

if tmp is None:
if getValue is None:
pass
else:
v = IDF[1](tmp)
v = string_to_idfdata(getValue.split(','), idfParams)
if v is not None:
if IDFcache[IDF[0]].qsize():
IDFcache[IDF[0]].get()
IDFcache[IDF[0]].put(v)
print('BClient.get [%s]: %s.' % (idfName, v))
if IDFcache[idfName].qsize():
IDFcache[idfName].get()
IDFcache[idfName].put(v)
else:
IDFcache[IDF[0]].put(v)
IDFcache[idfName].put(v)
timestamp = time.time()


Expand Down
Loading

0 comments on commit 554d502

Please sign in to comment.