2017年12月21日 星期四

Modbus TCP Slaver using Python modbus-tk lib


https://github.com/ljean/modbus-tk/

install pip…
sudo apt-get install python-pip

install...
download modbus_tk-x.x.x.tar.gz
tar zxvf modbus_tk-x.x.x.tar.gz
python setup.py install

make sure your port is open...
sudo iptables -A INPUT -p tcp --dport 502 -j ACCEPT # for slaver
sudo iptables -A OUTPUT -p tcp --dport 502 -j ACCEPT  # for master

run example as root
a simple example...
import sys
import logging
import threading
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus as modbus
import modbus_tk.modbus_tcp as modbus_tcp
import time

logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
# CREATE server
server = modbus_tcp.TcpServer() #DEFAULT PORT=502
slaver = server.add_slave(1) #ID=1

def setup():
    slaver.add_block("coil", cst.COILS, 0, 16)
    slaver.set_values("coil", 0, 16*[0])
       
def loop():
    logger.info("running...")
    # START
    server.start()
    while True:
        values = slaver.get_values("coil", 0, 8)
        #print values[0]
        str = ''
        for i in range(0, 8):
            if values[i] == 1:
                str = str + '1'
            else:
                str = str + '0'
        print  str
        # DELAY
        time.sleep(1)
        
def destory():
    logger.info("destory")
    # STOP
    server.stop()
       
if __name__ == "__main__":
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destory()


RaspberryPi BLE bluepy



install…
sudo apt-get install bluez
sudo hciconfig hci0 up

scan…
sudo hcitool lescan

or scan if no response...
sudo bluetoothctl
agent on
default-agent
scan on

other test...
using bluetoothctl

install bluepy…
https://github.com/IanHarvey/bluepy
sudo apt-get install python-pip libglib2.0-dev
sudo pip install bluepy

python test code…
from bluepy import btle
from bluepy.btle import Scanner, DefaultDelegate
import time
# Scan Delegate... 
class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

print 'Scanning...'
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(3.0)

address = None
for dev in devices:
    print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
    for (adtype, desc, value) in dev.getScanData():
        print "  %s = %s" % (desc, value)
        if desc == 'Complete Local Name' and value == 'YOUR_BLE_DEVICE_NAME':
            address = dev.addr

print "Connecting..."

#address = "YOUR_FIX_DEVICE_MAC"
dev = btle.Peripheral( address )

print "Services..."
for svc in dev.services:
    print str(svc)
    chs = svc.getCharacteristics()
    for ch in chs:
        print '  ' + str(ch)
# Notification Delegate
class MyDelegate(btle.DefaultDelegate):
    def __init__(self):
        btle.DefaultDelegate.__init__(self)
        # ... initialise here

    def handleNotification(self, cHandle, data):
        print 'handleNotification:' + str(data)
        # ... perhaps check cHandle
        # ... process 'data'


# Initialisation  -------

dev.setDelegate( MyDelegate() )

service_uuid = btle.UUID("49535343-fe7d-4ae5-8fa9-9fafd205e455") # YOUR SERVICE UUID
char_uuid = btle.UUID("49535343-1e4d-4bd9-ba61-23c647249616") # YOUR CHARACTERISTICS UUID

# Setup to turn notifications on, e.g.
svc = dev.getServiceByUUID( service_uuid )
ch = svc.getCharacteristics( char_uuid )[0]
# Here is how to write a value to Notification Characteristic... 
write_handle = ch.getHandle()
notify_handle = ch.getHandle() + 1
dev.writeCharacteristic( notify_handle, bytes("\x01"), withResponse=True)

time.sleep(1.0)

# Main loop --------
while True:
    if dev.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print "Waiting..."
    # Perhaps do something else here
    # Here is how to write a value to Characteristic
    dev.writeCharacteristic( write_handle, bytes("A"), False ) # YOUR DATA

更高效處理 micro second 的方式

更高效處理 micro second 的方式…  以 STM32 為例… __IO unsigned long sys_tick = 0; void SysTick_Handler(void) {     HAL_IncTick();     sys_tick += (SysTi...