增加高压空闲调节

This commit is contained in:
2026-06-10 11:23:24 +08:00
parent ee45729b5b
commit d44140d999
123 changed files with 22413 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+377
View File
@@ -0,0 +1,377 @@
<h3>
<p align="center">
Also check out the new ESP32 MPY-Jama free IDE and the latest MicroWebSrv2 below:
</p>
</h3>
<p align="center">
<a href="https://github.com/jczic/ESP32-MPY-Jama"><img src="https://github.com/jczic/ESP32-MPY-Jama/raw/master/img/ESP32%20MPY-Jama%20NEW.png" alt="New microWebSrv2" width="350" valign="middle"></a>                  
<a href="https://github.com/jczic/MicroWebSrv2"><img src="microWebSrv2.png" alt="New microWebSrv2" width="350" valign="middle"></a>
</p>
---
<br />
### MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and [Pycom](http://www.pycom.io) modules. Now supports all variants of [Pyboard D-series](https://store.micropython.org/category/pyboard%20D-series) from the makers of Micropython)
![HC²](hc2.png "HC²")
Very easy to integrate and very light with 3 files only :
- `"microWebSrv.py"` - The Web server
- `"microWebSocket.py"` - The optional support of WebSockets
- `"microWebTemplate.py"` - The optional templating language for **.pyhtml** rendered pages
Mini tuto in video by rdagger68 :
- [https://www.youtube.com/watch?v=xscBwC1SrF4](https://www.youtube.com/watch?v=xscBwC1SrF4)
Simple but effective :
- Use it to embed a cool Web site in yours modules
- Handle GET, POST, ... requests to interract with user and configure options
- Exchange in JSON format on HTTP methods to make an embedded fullREST API
- Serve files on the fly to export any data to the user
- Use routes and variable route handlers
- Play with AjAX to interact speedly with a Web application
- Make it a captive portal simply
- Use WebSockets for fast and powerful data exchange
- Make html/python files for rendering more efficient web pages
### Using *microWebSrv* main class :
| Name | Function |
| - | - |
| Constructor | `mws = MicroWebSrv(routeHandlers=None, port=80, bindIP='0.0.0.0', webPath="/flash/www")` |
| Start Web server | `mws.Start(threaded=True)` |
| Stop Web server | `mws.Stop()` |
| Check if Web server is running | `mws.IsStarted()` |
| Set URL location for not found page | `mws.SetNotFoundPageUrl(url=None)` |
| Get mime type from file extention | `mws.GetMimeTypeFromFilename(filename)` |
| Get handler function from route | `(routeHandler, routeArgs) = mws.GetRouteHandler(resUrl, method)` |
| Callback function to enable and accept WebSockets | `mws.AcceptWebSocketCallback = _acptWS` `_acptWS(webSocket, httpClient) { }` |
| Maximum length of memory allocated to receive WebSockets data (1024 by default) | `mws.MaxWebSocketRecvLen` |
| New thread used for each WebSocket connection (True by default) | `mws.WebSocketThreaded` |
| Escape string to HTML usage | `MicroWebSrv.HTMLEscape(s)` |
### Basic example :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.Start(threaded=True) # Starts server in a new thread
```
### Using as captive portal :
```python
# To intercept all not found queries and redirect it,
mws.SetNotFoundPageUrl("http://my-device.wifi")
```
- Can be used with [MicroDNSSrv](http://microdnssrv.hc2.fr) easily.
### Using route handlers example :
```python
routeHandlers = [
( "relative_url_route_1", "METHOD", handlerFunc_1 ),
( "relative_url_route_2", "METHOD", handlerFunc_2 ),
( ... )
]
```
```python
def handlerFunc_1(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 1")
def handlerFunc_2(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 2")
```
### Using directly route handlers decorators example :
```python
@MicroWebSrv.route('/get-test')
def handlerFuncGet(httpClient, httpResponse) :
print("In GET-TEST HTTP")
@MicroWebSrv.route('/post-test', 'POST')
def handlerFuncPost(httpClient, httpResponse) :
print("In POST-TEST HTTP")
```
### Using variable routes example :
```python
routeHandlers = [
( "/edit/<testid>/<testpath>", "GET", handlerFuncEdit ),
( ... )
]
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
Or direclty with route handler decorator :
```python
@MicroWebSrv.route('/edit/<testid>/<testpath>')
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
### Using *httpClient* class in a route handler function :
| Name | Function |
| - | - |
| Get MicroWebSrv class | `httpClient.GetServer()` |
| Get client address as tuple | `httpClient.GetAddr()` |
| Get client IP address | `httpClient.GetIPAddr()` |
| Get client TCP port | `httpClient.GetPort()` |
| Get client request method | `httpClient.GetRequestMethod()` |
| Get client request total path | `httpClient.GetRequestTotalPath()` |
| Get client request ressource path | `httpClient.GetRequestPath()` |
| Get client request query string | `httpClient.GetRequestQueryString()` |
| Get client request query parameters as list | `httpClient.GetRequestQueryParams()` |
| Get client request headers as list | `httpClient.GetRequestHeaders()` |
| Get client request content type | `httpClient.GetRequestContentType()` |
| Get client request content length | `httpClient.GetRequestContentLength()` |
| Get client request content | `httpClient.ReadRequestContent(size=None)` |
| Get client request form data as list | `httpClient.ReadRequestPostedFormData()` |
| Get client request as JSON object | `httpClient.ReadRequestContentAsJSON()` |
### Using *httpResponse* class in a route handler function :
| Name | Function |
| - | - |
| Write switching protocols response | `httpResponse.WriteSwitchProto(upgrade, headers=None)` |
| Write generic response | `httpResponse.WriteResponse(code, headers, contentType, contentCharset, content)` |
| Write PyHTML rendered response page | `httpResponse.WriteResponsePyHTMLFile(filepath, headers=None, vars=None)` |
| Write file directly as response | `httpResponse.WriteResponseFile(filepath, contentType=None, headers=None)` |
| Write attached file as response | `httpResponse.WriteResponseFileAttachment(filepath, attachmentName, headers=None)` |
| Write OK response | `httpResponse.WriteResponseOk(headers=None, contentType=None, contentCharset=None, content=None)` |
| Write JSON object as OK response | `httpResponse.WriteResponseJSONOk(obj=None, headers=None)` |
| Write redirect response | `httpResponse.WriteResponseRedirect(location)` |
| Write error response | `httpResponse.WriteResponseError(code)` |
| Write JSON object as error response | `httpResponse.WriteResponseJSONError(code, obj=None)` |
| Write bad request response | `httpResponse.WriteResponseBadRequest()` |
| Write forbidden response | `httpResponse.WriteResponseForbidden()` |
| Write not found response | `httpResponse.WriteResponseNotFound()` |
| Write method not allowed response | `httpResponse.WriteResponseMethodNotAllowed()` |
| Write internal server error response | `httpResponse.WriteResponseInternalServerError()` |
| Write not implemented response | `httpResponse.WriteResponseNotImplemented()` |
### Using route handler function example :
```python
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
```
### Known mime types (content types) :
| File extension | Mime type |
| - | - |
| .txt | text/plain |
| .htm | text/html |
| .html | text/html |
| .css | text/css |
| .csv | text/csv |
| .js | application/javascript |
| .xml | application/xml |
| .xhtml | application/xhtml+xml |
| .json | application/json |
| .zip | application/zip |
| .pdf | application/pdf |
| .ts | application/typescript |
| .woff | font/woff |
| .woff2 | font/woff2 |
| .ttf | font/ttf |
| .otf | font/otf |
| .jpg | image/jpeg |
| .jpeg | image/jpeg |
| .png | image/png |
| .gif | image/gif |
| .svg | image/svg+xml |
| .ico | image/x-icon |
### Default index pages order (for http://hostname/) :
| Filename |
| - |
| index.pyhtml |
| index.html |
| index.htm |
| default.pyhtml |
| default.html |
| default.htm |
### Using optional module *microWebSocket* to connect WebSockets :
- File `"microWebSocket.py"` must be present to activate WebSockets support
### Enable and accept WebSockets :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.MaxWebSocketRecvLen = 256 # Default is set to 1024
mws.WebSocketThreaded = False # WebSockets without new threads
mws.AcceptWebSocketCallback = _acceptWebSocketCallback # Function to receive WebSockets
mws.Start(threaded=True) # Starts server in a new thread
```
| Name | Function |
| - | - |
| Callback function to receive text message | `ws.RecvTextCallback = func(webSocket, msg)` |
| Callback function to receive binary data | `ws.RecvBinaryCallback = func(webSocket, data)` |
| Callback function when connection was closed | `ws.ClosedCallback = func(webSocket)` |
| Send a text message | `ws.SendText(msg)` |
| Send a binary message | `ws.SendBinary(data)` |
| Check connection state | `ws.IsClosed()` |
| Close the connection | `ws.Close()` |
### Basic example of callback functions :
```python
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
```
### Using optional module *microWebTemplate* for *.pyhtml* rendered pages :
- File `"microWebTemplate.py"` must be present to activate **.pyhtml** pages
- Pages will be rendered in HTML with integrated MicroPython code
| Instruction | Schema |
| - | - |
| PY | `{{ py }}` *MicroPython code* `{{ end }}` |
| IF | `{{ if` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELIF | `{{ elif` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELSE | `{{ else }}` *html bloc* `{{ end }}` |
| FOR | `{{ for` *identifier* `in` *MicroPython iterator* `}}` *html bloc* `{{ end }}` |
| INCLUDE | `{{ include` *pyhtml_filename* `}}` |
| ?   | `{{` *MicroPython expression* `}}` |
### Using {{ py }} :
```python
{{ py }}
import machine
from utime import sleep
test = 123
def testFunc(x) :
return 2 * x
{{ end }}
```
### Using {{ if ... }} :
```python
{{ if testFunc(5) <= 3 }}
<span>titi</span>
{{ elif testFunc(10) >= 15 }}
<span>tata</span>
{{ else }}
<span>I like the number {{ test }} !</span>
{{ end }}
```
### Using {{ for ... }} :
```python
{{ for toto in range(testFunc(3)) }}
<div>toto x 10 equal {{ toto * 10 }}</div>
<hr />
{{ end }}
```
### Using {{ include ... }} :
```python
{{ include myTemplate.pyhtml }}
```
### Example of a .pyhtml file :
```html
<html>
<head>
<title>TEST PYHTML</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
</body>
</html>
```
<a name="author"></a>
## :wink: &nbsp;Author
**Jean-Christophe Bos** (:fr:)
- GitHub: *[@jczic](https://github.com/jczic)*
- Email: *<jczic.bos@gmail.com>*
- Profil: *[LinkedIn](https://www.linkedin.com/in/jczic)*
- Music: *[SoundCloud](https://soundcloud.com/jczic/sets/electro-pulse)*
*[Spotify](https://open.spotify.com/album/5fUd57GcAIcdUn9NX3fviG)*
*[YouTube](https://www.youtube.com/playlist?list=PL9CsGuMbcLaU02VKS7jtR6LaDNpq7MZEq)*
### By JC`zic for [HC²](https://www.hc2.fr) ;')
*Keep it simple, stupid* :+1:
+2
View File
@@ -0,0 +1,2 @@
show_downloads: true
theme: jekyll-theme-midnight
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+121
View File
@@ -0,0 +1,121 @@
from microWebSrv import MicroWebSrv
# ----------------------------------------------------------------------------
@MicroWebSrv.route('/test')
def _httpHandlerTestGet(httpClient, httpResponse) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST GET</title>
</head>
<body>
<h1>TEST GET</h1>
Client IP address = %s
<br />
<form action="/test" method="post" accept-charset="ISO-8859-1">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
""" % httpClient.GetIPAddr()
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/test', 'POST')
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/edit/<index>') # <IP>/edit/123 -> args['index']=123
@MicroWebSrv.route('/edit/<index>/abc/<foo>') # <IP>/edit/123/abc/bar -> args['index']=123 args['foo']='bar'
@MicroWebSrv.route('/edit') # <IP>/edit -> args={}
def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST EDIT</title>
</head>
<body>
"""
content += "<h1>EDIT item with {} variable arguments</h1>"\
.format(len(args))
if 'index' in args :
content += "<p>index = {}</p>".format(args['index'])
if 'foo' in args :
content += "<p>foo = {}</p>".format(args['foo'])
content += """
</body>
</html>
"""
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
# ----------------------------------------------------------------------------
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
# ----------------------------------------------------------------------------
#routeHandlers = [
# ( "/test", "GET", _httpHandlerTestGet ),
# ( "/test", "POST", _httpHandlerTestPost )
#]
srv = MicroWebSrv(webPath='/web_root/web_admin/')
srv.MaxWebSocketRecvLen = 256
srv.WebSocketThreaded = False
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
srv.Start()
# ----------------------------------------------------------------------------
+284
View File
@@ -0,0 +1,284 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from hashlib import sha1
from binascii import b2a_base64
from struct import pack
from _thread import start_new_thread, allocate_lock
import gc
class MicroWebSocket :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_handshakeSign = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
_opContFrame = 0x0
_opTextFrame = 0x1
_opBinFrame = 0x2
_opCloseFrame = 0x8
_opPingFrame = 0x9
_opPongFrame = 0xA
_msgTypeText = 1
_msgTypeBin = 2
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@staticmethod
def _tryAllocByteArray(size) :
for x in range(10) :
try :
gc.collect()
return bytearray(size)
except :
pass
return None
# ----------------------------------------------------------------------------
@staticmethod
def _tryStartThread(func, args=()) :
for x in range(10) :
try :
gc.collect()
start_new_thread(func, args)
return True
except :
global _mws_thread_id
try :
_mws_thread_id += 1
except :
_mws_thread_id = 0
try :
start_new_thread('MWS_THREAD_%s' % _mws_thread_id, func, args)
return True
except :
pass
return False
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
self._socket = socket
self._httpCli = httpClient
self._closed = True
self._lock = allocate_lock()
self.RecvTextCallback = None
self.RecvBinaryCallback = None
self.ClosedCallback = None
if hasattr(socket, 'read'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
if self._handshake(httpResponse) :
self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
self._msgBuf = MicroWebSocket._tryAllocByteArray(maxRecvLen)
if self._ctrlBuf and self._msgBuf :
self._msgType = None
self._msgLen = 0
if threaded :
if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
return
else :
self._wsProcess(acceptCallback)
return
print("MicroWebSocket : Out of memory on new WebSocket connection.")
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def _handshake(self, httpResponse) :
try :
key = self._httpCli.GetRequestHeaders().get('sec-websocket-key', None)
if key :
key += self._handshakeSign
r = sha1(key.encode()).digest()
r = b2a_base64(r).decode().strip()
httpResponse.WriteSwitchProto("websocket", { "Sec-WebSocket-Accept" : r })
return True
except :
pass
return False
# ----------------------------------------------------------------------------
def _wsProcess(self, acceptCallback) :
self._socket.settimeout(3600)
self._closed = False
try :
acceptCallback(self, self._httpCli)
except Exception as ex :
print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
while not self._closed :
if not self._receiveFrame() :
self.Close()
if self.ClosedCallback :
try :
self.ClosedCallback(self)
except Exception as ex :
print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
# ----------------------------------------------------------------------------
def _receiveFrame(self) :
try :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
fin = b[0] & 0x80 > 0
opcode = b[0] & 0x0F
masked = b[1] & 0x80 > 0
length = b[1] & 0x7F
if opcode == self._opContFrame and not self._msgType :
return False
elif opcode == self._opTextFrame :
self._msgType = self._msgTypeText
elif opcode == self._opBinFrame :
self._msgType = self._msgTypeBin
if length == 0x7E :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
length = (b[0] << 8) + b[1]
elif length == 0x7F :
return False
mask = self._socketfile.read(4) if masked else None
if masked and (not mask or len(mask) != 4) :
return False
if opcode == self._opContFrame or \
opcode == self._opTextFrame or \
opcode == self._opBinFrame :
if length > 0 :
buf = memoryview(self._msgBuf)[self._msgLen:]
if length > len(buf) :
return False
x = self._socketfile.readinto(buf[0:length])
if x != length :
return False
if masked :
for i in range(length) :
idx = self._msgLen + i
self._msgBuf[idx] ^= mask[i%4]
self._msgLen += length
if fin :
b = bytes(memoryview(self._msgBuf)[:self._msgLen])
if self._msgType == self._msgTypeText :
if self.RecvTextCallback :
try :
self.RecvTextCallback(self, b.decode())
except Exception as ex :
print("MicroWebSocket : Error on recv text callback (%s)." % str(ex))
else :
if self.RecvBinaryCallback :
try :
self.RecvBinaryCallback(self, b)
except Exception as ex :
print("MicroWebSocket : Error on recv binary callback (%s)." % str(ex))
self._msgType = None
self._msgLen = 0
else :
return False
elif opcode == self._opPingFrame :
if length > len(self._ctrlBuf) :
return False
if length > 0 :
x = self._socketfile.readinto(self._ctrlBuf[0:length])
if x != length :
return False
pingData = memoryview(self._ctrlBuf)[:length]
else :
pingData = None
self._sendFrame(self._opPongFrame, pingData)
elif opcode == self._opCloseFrame :
self.Close()
except :
return False
return True
# ----------------------------------------------------------------------------
def _sendFrame(self, opcode, data=None, fin=True) :
if not self._closed and opcode >= 0x00 and opcode <= 0x0F :
dataLen = 0 if not data else len(data)
if dataLen <= 0xFFFF :
b1 = (0x80 | opcode) if fin else opcode
b2 = 0x7E if dataLen >= 0x7E else dataLen
self._lock.acquire()
try :
if self._socketfile.write(pack('>BB', b1, b2)) == 2 :
if dataLen > 0 :
if dataLen >= 0x7E :
self._socketfile.write(pack('>H', dataLen))
ret = self._socketfile.write(data) == dataLen
else :
ret = True
if self._socketfile is not self._socket :
self._socketfile.flush() # CPython needs flush to continue protocol
self._lock.release()
return ret
except :
pass
self._lock.release()
return False
# ----------------------------------------------------------------------------
def SendText(self, msg) :
return self._sendFrame(self._opTextFrame, msg.encode())
# ----------------------------------------------------------------------------
def SendBinary(self, data) :
return self._sendFrame(self._opBinFrame, data)
# ----------------------------------------------------------------------------
def IsClosed(self) :
return self._closed
# ----------------------------------------------------------------------------
def Close(self) :
if not self._closed :
try :
self._sendFrame(self._opCloseFrame)
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
self._closed = True
except :
pass
# ============================================================================
# ============================================================================
# ============================================================================
+881
View File
@@ -0,0 +1,881 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from json import loads, dumps
from os import stat
from _thread import start_new_thread
import socket
import gc
import re
try :
from microWebTemplate import MicroWebTemplate
except :
pass
try :
from microWebSocket import MicroWebSocket
except :
print("MicroWebSrv: MicroWebSocket module not found, WebSocket support disabled")
pass
class MicroWebSrvRoute :
def __init__(self, route, method, func, routeArgNames, routeRegex) :
self.route = route
self.method = method
self.func = func
self.routeArgNames = routeArgNames
self.routeRegex = routeRegex
class MicroWebSrv :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_indexPages = [
"index.pyhtml",
"index.html",
"index.htm",
"default.pyhtml",
"default.html",
"default.htm"
]
_mimeTypes = {
".txt" : "text/plain",
".htm" : "text/html",
".html" : "text/html",
".css" : "text/css",
".csv" : "text/csv",
".js" : "application/javascript",
".xml" : "application/xml",
".xhtml" : "application/xhtml+xml",
".json" : "application/json",
".zip" : "application/zip",
".pdf" : "application/pdf",
".ts" : "application/typescript",
".woff" : "font/woff",
".woff2" : "font/woff2",
".ttf" : "font/ttf",
".otf" : "font/otf",
".jpg" : "image/jpeg",
".jpeg" : "image/jpeg",
".png" : "image/png",
".gif" : "image/gif",
".svg" : "image/svg+xml",
".ico" : "image/x-icon"
}
_html_escape_chars = {
"&" : "&amp;",
'"' : "&quot;",
"'" : "&apos;",
">" : "&gt;",
"<" : "&lt;"
}
_pyhtmlPagesExt = '.pyhtml'
# ============================================================================
# ===( Class globals )=======================================================
# ============================================================================
_docoratedRouteHandlers = []
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@classmethod
def route(cls, url, method='GET'):
""" Adds a route handler function to the routing list """
def route_decorator(func):
item = (url, method, func)
cls._docoratedRouteHandlers.append(item)
return func
return route_decorator
# ----------------------------------------------------------------------------
@staticmethod
def HTMLEscape(s) :
return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s)
# ----------------------------------------------------------------------------
@staticmethod
def _startThread(func, args=()) :
try :
start_new_thread(func, args)
except :
global _mwsrv_thread_id
try :
_mwsrv_thread_id += 1
except :
_mwsrv_thread_id = 0
try :
start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args)
except :
return False
return True
# ----------------------------------------------------------------------------
@staticmethod
def _unquote(s) :
r = str(s).split('%')
try :
b = r[0].encode()
for i in range(1, len(r)) :
try :
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
except :
b += b'%' + r[i].encode()
return b.decode('UTF-8')
except :
return str(s)
# ------------------------------------------------------------------------------
@staticmethod
def _unquote_plus(s) :
return MicroWebSrv._unquote(s.replace('+', ' '))
# ------------------------------------------------------------------------------
@staticmethod
def _fileExists(path) :
try :
stat(path)
return True
except :
return False
# ----------------------------------------------------------------------------
@staticmethod
def _isPyHTMLFile(filename) :
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__( self,
routeHandlers = [],
port = 80,
bindIP = '0.0.0.0',
webPath = "/flash/www" ) :
self._srvAddr = (bindIP, port)
self._webPath = webPath
self._notFoundUrl = None
self._started = False
self.MaxWebSocketRecvLen = 1024
self.WebSocketThreaded = True
self.AcceptWebSocketCallback = None
self.LetCacheStaticContentLevel = 2
self._routeHandlers = []
routeHandlers += self._docoratedRouteHandlers
for route, method, func in routeHandlers :
routeParts = route.split('/')
# -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>']
routeArgNames = []
routeRegex = ''
for s in routeParts :
if s.startswith('<') and s.endswith('>') :
routeArgNames.append(s[1:-1])
routeRegex += '/(\\w*)'
elif s :
routeRegex += '/' + s
routeRegex += '$'
# -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
routeRegex = re.compile(routeRegex)
self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex))
# ============================================================================
# ===( Server Process )=======================================================
# ============================================================================
def _serverProcess(self) :
self._started = True
while True :
try :
client, cliAddr = self._server.accept()
except Exception as ex :
if ex.args and ex.args[0] == 113 :
break
continue
self._client(self, client, cliAddr)
self._started = False
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Start(self, threaded=False) :
if not self._started :
self._server = socket.socket()
self._server.setsockopt( socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1 )
self._server.bind(self._srvAddr)
self._server.listen(16)
if threaded :
MicroWebSrv._startThread(self._serverProcess)
else :
self._serverProcess()
# ----------------------------------------------------------------------------
def Stop(self) :
if self._started :
self._server.close()
# ----------------------------------------------------------------------------
def IsStarted(self) :
return self._started
# ----------------------------------------------------------------------------
def SetNotFoundPageUrl(self, url=None) :
self._notFoundUrl = url
# ----------------------------------------------------------------------------
def GetMimeTypeFromFilename(self, filename) :
filename = filename.lower()
for ext in self._mimeTypes :
if filename.endswith(ext) :
return self._mimeTypes[ext]
return None
# ----------------------------------------------------------------------------
def GetRouteHandler(self, resUrl, method) :
if self._routeHandlers :
#resUrl = resUrl.upper()
if resUrl.endswith('/') :
resUrl = resUrl[:-1]
method = method.upper()
for rh in self._routeHandlers :
if rh.method == method :
m = rh.routeRegex.match(resUrl)
if m : # found matching route?
if rh.routeArgNames :
routeArgs = {}
for i, name in enumerate(rh.routeArgNames) :
value = m.group(i+1)
try :
value = int(value)
except :
pass
routeArgs[name] = value
return (rh.func, routeArgs)
else :
return (rh.func, None)
return (None, None)
# ----------------------------------------------------------------------------
def _physPathFromURLPath(self, urlPath) :
if urlPath == '/' :
for idxPage in self._indexPages :
physPath = self._webPath + '/' + idxPage
if MicroWebSrv._fileExists(physPath) :
return physPath
else :
physPath = self._webPath + urlPath.replace('../', '/')
if MicroWebSrv._fileExists(physPath) :
return physPath
return None
# ============================================================================
# ===( Class Client )========================================================
# ============================================================================
class _client :
# ------------------------------------------------------------------------
def __init__(self, microWebSrv, socket, addr) :
socket.settimeout(2)
self._microWebSrv = microWebSrv
self._socket = socket
self._addr = addr
self._method = None
self._path = None
self._httpVer = None
self._resPath = "/"
self._queryString = ""
self._queryParams = { }
self._headers = { }
self._contentType = None
self._contentLength = 0
if hasattr(socket, 'readline'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
self._processRequest()
# ------------------------------------------------------------------------
def _processRequest(self) :
try :
response = MicroWebSrv._response(self)
if self._parseFirstLine(response) :
if self._parseHeader(response) :
upg = self._getConnUpgrade()
if not upg :
routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method)
if routeHandler :
try :
if routeArgs is not None:
routeHandler(self, response, routeArgs)
else :
routeHandler(self, response)
except Exception as ex :
print('MicroWebSrv handler exception:\r\n - In route %s %s\r\n - %s' % (self._method, self._resPath, ex))
raise ex
elif self._method.upper() == "GET" :
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
if filepath :
if MicroWebSrv._isPyHTMLFile(filepath) :
response.WriteResponsePyHTMLFile(filepath)
else :
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
if contentType :
if self._microWebSrv.LetCacheStaticContentLevel > 0 :
if self._microWebSrv.LetCacheStaticContentLevel > 1 and \
'if-modified-since' in self._headers :
response.WriteResponseNotModified()
else:
headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \
'Cache-Control' : 'max-age=315360000' }
response.WriteResponseFile(filepath, contentType, headers)
else :
response.WriteResponseFile(filepath, contentType)
else :
response.WriteResponseForbidden()
else :
response.WriteResponseNotFound()
else :
response.WriteResponseMethodNotAllowed()
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
and self._microWebSrv.AcceptWebSocketCallback :
MicroWebSocket( socket = self._socket,
httpClient = self,
httpResponse = response,
maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen,
threaded = self._microWebSrv.WebSocketThreaded,
acceptCallback = self._microWebSrv.AcceptWebSocketCallback )
return
else :
response.WriteResponseNotImplemented()
else :
response.WriteResponseBadRequest()
except :
response.WriteResponseInternalServerError()
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ------------------------------------------------------------------------
def _parseFirstLine(self, response) :
try :
elements = self._socketfile.readline().decode().strip().split()
if len(elements) == 3 :
self._method = elements[0].upper()
self._path = elements[1]
self._httpVer = elements[2].upper()
elements = self._path.split('?', 1)
if len(elements) > 0 :
self._resPath = MicroWebSrv._unquote_plus(elements[0])
if len(elements) > 1 :
self._queryString = elements[1]
elements = self._queryString.split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else ''
self._queryParams[MicroWebSrv._unquote(param[0])] = value
return True
except :
pass
return False
# ------------------------------------------------------------------------
def _parseHeader(self, response) :
while True :
elements = self._socketfile.readline().decode().strip().split(':', 1)
if len(elements) == 2 :
self._headers[elements[0].strip().lower()] = elements[1].strip()
elif len(elements) == 1 and len(elements[0]) == 0 :
if self._method == 'POST' or self._method == 'PUT' :
self._contentType = self._headers.get("content-type", None)
self._contentLength = int(self._headers.get("content-length", 0))
return True
else :
return False
# ------------------------------------------------------------------------
def _getConnUpgrade(self) :
if 'upgrade' in self._headers.get('connection', '').lower() :
return self._headers.get('upgrade', '').lower()
return None
# ------------------------------------------------------------------------
def GetServer(self) :
return self._microWebSrv
# ------------------------------------------------------------------------
def GetAddr(self) :
return self._addr
# ------------------------------------------------------------------------
def GetIPAddr(self) :
return self._addr[0]
# ------------------------------------------------------------------------
def GetPort(self) :
return self._addr[1]
# ------------------------------------------------------------------------
def GetRequestMethod(self) :
return self._method
# ------------------------------------------------------------------------
def GetRequestTotalPath(self) :
return self._path
# ------------------------------------------------------------------------
def GetRequestPath(self) :
return self._resPath
# ------------------------------------------------------------------------
def GetRequestQueryString(self) :
return self._queryString
# ------------------------------------------------------------------------
def GetRequestQueryParams(self) :
return self._queryParams
# ------------------------------------------------------------------------
def GetRequestHeaders(self) :
return self._headers
# ------------------------------------------------------------------------
def GetRequestContentType(self) :
return self._contentType
# ------------------------------------------------------------------------
def GetRequestContentLength(self) :
return self._contentLength
# ------------------------------------------------------------------------
def ReadRequestContent(self, size=None) :
if size is None :
size = self._contentLength
if size > 0 :
try :
return self._socketfile.read(size)
except :
pass
return b''
# ------------------------------------------------------------------------
def ReadRequestPostedFormData(self) :
res = { }
data = self.ReadRequestContent()
if data :
elements = data.decode().split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote_plus(param[1]) if len(param) > 1 else ''
res[MicroWebSrv._unquote_plus(param[0])] = value
return res
# ------------------------------------------------------------------------
def ReadRequestContentAsJSON(self) :
data = self.ReadRequestContent()
if data :
try :
return loads(data.decode())
except :
pass
return None
# ============================================================================
# ===( Class Response )======================================================
# ============================================================================
class _response :
# ------------------------------------------------------------------------
def __init__(self, client) :
self._client = client
# ------------------------------------------------------------------------
def _write(self, data, strEncoding='ISO-8859-1') :
if data :
if type(data) == str :
data = data.encode(strEncoding)
data = memoryview(data)
while data :
n = self._client._socketfile.write(data)
if n is None :
return False
data = data[n:]
return True
return False
# ------------------------------------------------------------------------
def _writeFirstLine(self, code) :
reason = self._responseCodes.get(code, ('Unknown reason', ))[0]
return self._write("HTTP/1.1 %s %s\r\n" % (code, reason))
# ------------------------------------------------------------------------
def _writeHeader(self, name, value) :
return self._write("%s: %s\r\n" % (name, value))
# ------------------------------------------------------------------------
def _writeContentTypeHeader(self, contentType, charset=None) :
if contentType :
ct = contentType \
+ (("; charset=%s" % charset) if charset else "")
else :
ct = "application/octet-stream"
self._writeHeader("Content-Type", ct)
# ------------------------------------------------------------------------
def _writeServerHeader(self) :
self._writeHeader("Server", "MicroWebSrv by JC`zic")
# ------------------------------------------------------------------------
def _writeEndHeader(self) :
return self._write("\r\n")
# ------------------------------------------------------------------------
def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) :
self._writeFirstLine(code)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
if contentLength > 0 :
self._writeContentTypeHeader(contentType, contentCharset)
self._writeHeader("Content-Length", contentLength)
self._writeServerHeader()
self._writeHeader("Connection", "close")
self._writeEndHeader()
# ------------------------------------------------------------------------
def WriteSwitchProto(self, upgrade, headers=None) :
self._writeFirstLine(101)
self._writeHeader("Connection", "Upgrade")
self._writeHeader("Upgrade", upgrade)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
self._writeServerHeader()
self._writeEndHeader()
if self._client._socketfile is not self._client._socket :
self._client._socketfile.flush() # CPython needs flush to continue protocol
# ------------------------------------------------------------------------
def WriteResponse(self, code, headers, contentType, contentCharset, content) :
try :
if content :
if type(content) == str :
content = content.encode(contentCharset)
contentLength = len(content)
else :
contentLength = 0
self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength)
if content :
return self._write(content)
return True
except :
return False
# ------------------------------------------------------------------------
def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) :
if 'MicroWebTemplate' in globals() :
with open(filepath, 'r') as file :
code = file.read()
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
try :
tmplResult = mWebTmpl.Execute(None, vars)
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
except Exception as ex :
return self.WriteResponse( 500,
None,
"text/html",
"UTF-8",
self._execErrCtnTmpl % {
'module' : 'PyHTML',
'message' : str(ex)
} )
return self.WriteResponseNotImplemented()
# ------------------------------------------------------------------------
def WriteResponseFile(self, filepath, contentType=None, headers=None) :
try :
size = stat(filepath)[6]
if size > 0 :
with open(filepath, 'rb') as file :
self._writeBeforeContent(200, headers, contentType, None, size)
try :
buf = bytearray(1024)
while size > 0 :
x = file.readinto(buf)
if x < len(buf) :
buf = memoryview(buf)[:x]
if not self._write(buf) :
return False
size -= x
return True
except :
self.WriteResponseInternalServerError()
return False
except :
pass
self.WriteResponseNotFound()
return False
# ------------------------------------------------------------------------
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) :
if not isinstance(headers, dict) :
headers = { }
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
return self.WriteResponseFile(filepath, None, headers)
# ------------------------------------------------------------------------
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) :
return self.WriteResponse(200, headers, contentType, contentCharset, content)
# ------------------------------------------------------------------------
def WriteResponseJSONOk(self, obj=None, headers=None) :
return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj))
# ------------------------------------------------------------------------
def WriteResponseRedirect(self, location) :
headers = { "Location" : location }
return self.WriteResponse(302, headers, None, None, None)
# ------------------------------------------------------------------------
def WriteResponseError(self, code) :
responseCode = self._responseCodes.get(code, ('Unknown reason', ''))
return self.WriteResponse( code,
None,
"text/html",
"UTF-8",
self._errCtnTmpl % {
'code' : code,
'reason' : responseCode[0],
'message' : responseCode[1]
} )
# ------------------------------------------------------------------------
def WriteResponseJSONError(self, code, obj=None) :
return self.WriteResponse( code,
None,
"application/json",
"UTF-8",
dumps(obj if obj else { }) )
# ------------------------------------------------------------------------
def WriteResponseNotModified(self) :
return self.WriteResponseError(304)
# ------------------------------------------------------------------------
def WriteResponseBadRequest(self) :
return self.WriteResponseError(400)
# ------------------------------------------------------------------------
def WriteResponseForbidden(self) :
return self.WriteResponseError(403)
# ------------------------------------------------------------------------
def WriteResponseNotFound(self) :
if self._client._microWebSrv._notFoundUrl :
self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl)
else :
return self.WriteResponseError(404)
# ------------------------------------------------------------------------
def WriteResponseMethodNotAllowed(self) :
return self.WriteResponseError(405)
# ------------------------------------------------------------------------
def WriteResponseInternalServerError(self) :
return self.WriteResponseError(500)
# ------------------------------------------------------------------------
def WriteResponseNotImplemented(self) :
return self.WriteResponseError(501)
# ------------------------------------------------------------------------
def FlashMessage(self, messageText, messageStyle='') :
if 'MicroWebTemplate' in globals() :
MicroWebTemplate.MESSAGE_TEXT = messageText
MicroWebTemplate.MESSAGE_STYLE = messageStyle
# ------------------------------------------------------------------------
_errCtnTmpl = """\
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>%(code)d %(reason)s</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_execErrCtnTmpl = """\
<html>
<head>
<title>Page execution error</title>
</head>
<body>
<h1>%(module)s page execution error</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_responseCodes = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+336
View File
@@ -0,0 +1,336 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import re
class MicroWebTemplate :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
TOKEN_OPEN = '{{'
TOKEN_CLOSE = '}}'
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
INSTRUCTION_PYTHON = 'py'
INSTRUCTION_IF = 'if'
INSTRUCTION_ELIF = 'elif'
INSTRUCTION_ELSE = 'else'
INSTRUCTION_FOR = 'for'
INSTRUCTION_END = 'end'
INSTRUCTION_INCLUDE = 'include'
MESSAGE_TEXT = ''
MESSAGE_STYLE = ''
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, code, escapeStrFunc=None, filepath='') :
self._code = code
self._escapeStrFunc = escapeStrFunc
self._filepath = filepath
self._pos = 0
self._endPos = len(code)-1
self._line = 1
self._reIdentifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
self._pyGlobalVars = { }
self._pyLocalVars = { }
self._rendered = ''
self._instructions = {
MicroWebTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
MicroWebTemplate.INSTRUCTION_IF : self._processInstructionIF,
MicroWebTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
MicroWebTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
MicroWebTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
MicroWebTemplate.INSTRUCTION_END : self._processInstructionEND,
MicroWebTemplate.INSTRUCTION_INCLUDE: self._processInstructionINCLUDE,
}
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
return None
except Exception as ex :
return str(ex)
# ----------------------------------------------------------------------------
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
return self._rendered
except Exception as ex :
raise Exception(str(ex))
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
if pyGlobalVars:
self._pyGlobalVars.update(pyGlobalVars)
if pyLocalVars:
self._pyLocalVars.update(pyLocalVars)
self._pyLocalVars['MESSAGE_TEXT'] = MicroWebTemplate.MESSAGE_TEXT
self._pyLocalVars['MESSAGE_STYLE'] = MicroWebTemplate.MESSAGE_STYLE
self._rendered = ''
newTokenToProcess = self._parseBloc(execute)
if newTokenToProcess is not None :
raise Exception( '"%s" instruction is not valid here (line %s)'
% (newTokenToProcess, self._line) )
MicroWebTemplate.MESSAGE_TEXT = ''
MicroWebTemplate.MESSAGE_STYLE = ''
# ----------------------------------------------------------------------------
def _parseBloc(self, execute) :
while self._pos <= self._endPos :
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
newTokenToProcess = self._processToken(tokenContent, execute)
if newTokenToProcess is not None :
return newTokenToProcess
continue
elif c == '\n' :
self._line += 1
if execute :
self._rendered += c
self._pos += 1
return None
# ----------------------------------------------------------------------------
def _processToken(self, tokenContent, execute) :
tokenContent = tokenContent.strip()
parts = tokenContent.split(' ', 1)
instructName = parts[0].strip()
instructBody = parts[1].strip() if len(parts) > 1 else None
if len(instructName) == 0 :
raise Exception( '"%s %s" : instruction is missing (line %s)'
% (MicroWebTemplate.TOKEN_OPEN, MicroWebTemplate.TOKEN_CLOSE, self._line) )
newTokenToProcess = None
if instructName in self._instructions :
newTokenToProcess = self._instructions[instructName](instructBody, execute)
elif execute :
try :
s = str( eval( tokenContent,
self._pyGlobalVars,
self._pyLocalVars ) )
if (self._escapeStrFunc is not None) :
self._rendered += self._escapeStrFunc(s)
else :
self._rendered += s
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return newTokenToProcess
# ----------------------------------------------------------------------------
def _processInstructionPYTHON(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_PYTHON, self._line) )
pyCode = ''
while True :
if self._pos > self._endPos :
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
tokenContent = tokenContent.strip()
if tokenContent == MicroWebTemplate.INSTRUCTION_END :
break
raise Exception( '"%s" is a bad instruction in a python bloc (line %s)'
% (tokenContent, self._line) )
elif c == '\n' :
self._line += 1
if execute :
pyCode += c
self._pos += 1
if execute :
lines = pyCode.split('\n')
indent = ''
for line in lines :
if len(line.strip()) > 0 :
for c in line :
if c == ' ' or c == '\t' :
indent += c
else :
break
break
pyCode = ''
for line in lines :
if line.find(indent) == 0 :
line = line[len(indent):]
pyCode += line + '\n'
try :
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return None
# ----------------------------------------------------------------------------
def _processInstructionIF(self, instructionBody, execute) :
if instructionBody is not None :
if execute :
try :
if (' ' not in instructionBody) and \
('=' not in instructionBody) and \
('<' not in instructionBody) and \
('>' not in instructionBody) and \
(instructionBody not in self._pyGlobalVars) and \
(instructionBody not in self._pyLocalVars):
result = False
else:
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
else :
result = False
newTokenToProcess = self._parseBloc(execute and result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELSE :
newTokenToProcess = self._parseBloc(execute and not result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELIF :
self._processInstructionIF(self._elifInstructionBody, execute and not result)
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_IF, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionELIF(self, instructionBody, execute) :
if instructionBody is None :
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELIF, self._line) )
self._elifInstructionBody = instructionBody
return MicroWebTemplate.INSTRUCTION_ELIF
# ----------------------------------------------------------------------------
def _processInstructionELSE(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELSE, self._line) )
return MicroWebTemplate.INSTRUCTION_ELSE
# ----------------------------------------------------------------------------
def _processInstructionFOR(self, instructionBody, execute) :
if instructionBody is not None :
parts = instructionBody.split(' ', 1)
identifier = parts[0].strip()
if self._reIdentifier.match(identifier) is not None and len(parts) > 1 :
parts = parts[1].strip().split(' ', 1)
if parts[0] == 'in' and len(parts) > 1 :
expression = parts[1].strip()
newTokenToProcess = None
beforePos = self._pos
if execute :
try :
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
except :
raise Exception('%s (line %s)' % (str(expression), self._line))
if execute and len(result) > 0 :
for x in result :
self._pyLocalVars[identifier] = x
self._pos = beforePos
newTokenToProcess = self._parseBloc(True)
if newTokenToProcess != MicroWebTemplate.INSTRUCTION_END :
break
else :
newTokenToProcess = self._parseBloc(False)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s %s" is an invalid syntax'
% (MicroWebTemplate.INSTRUCTION_FOR, instructionBody) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_FOR, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionEND(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
return MicroWebTemplate.INSTRUCTION_END
# ----------------------------------------------------------------------------
def _processInstructionINCLUDE(self, instructionBody, execute) :
if not instructionBody :
raise Exception( '"%s" alone is an incomplete syntax (line %s)' % (MicroWebTemplate.INSTRUCTION_INCLUDE, self._line) )
filename = instructionBody.replace('"','').replace("'",'').strip()
idx = self._filepath.rindex('/')
if idx >= 0 :
filename = self._filepath[:idx+1] + filename
with open(filename, 'r') as file :
includeCode = file.read()
self._code = self._code[:self._pos] + includeCode + self._code[self._pos:]
self._endPos += len(includeCode)
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+28
View File
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>Page de test MicroWebSrv</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Page de test MicroWebSrv</h1>
<h2>Hello !</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
</p>
<br />
<hr />
<br />
<div style="text-align: center">
<img src="pdf.png" />
<p>
Afficher « <a href="test.pdf">un fichier PDF</a> »
</p>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+36
View File
@@ -0,0 +1,36 @@
html, body {
margin: 0;
padding: 0;
}
body {
background-color: white;
font-family: Verdana, sans-serif;
font-size: 100%;
}
h1 {
font-size: 200%;
color: navy;
text-align: center;
}
h2 {
font-size: 150%;
color: red;
padding-left: 15px;
}
p,ul,li,td {
color: black;
}
a:link {
color: green;
text-decoration: underline;
}
a:visited {
color: gray;
}
a:hover {
color: red;
text-decoration: none;
}
a:active, a:focus {
color: red;
}
Binary file not shown.
+34
View File
@@ -0,0 +1,34 @@
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
<h1>JC :')</h1>
</body>
</html>
+78
View File
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSocket Test</title>
</head>
<script language="javascript">
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
var wsUri = "ws://" + window.location.hostname;
writeToScreen("Connection to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
}
function onOpen(evt)
{
writeToScreen("<strong>-- CONNECTED --</strong>");
SendMsg("Hello world :)");
SendMsg("This is a WebSocket test");
SendMsg("(with a text frame encoded in UTF-8)");
setTimeout( function() { websocket.close() }, 500 )
}
function onClose(evt)
{
writeToScreen("<strong>-- DISCONNECTED --</strong>");
}
function onMessage(evt)
{
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
}
function onError(evt)
{
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
}
function SendMsg(msg)
{
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
websocket.send(msg);
}
function writeToScreen(s)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = s;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>MicroWebSocket Test :</h2>
<div id="output"></div>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
rm /download/bootloader.bin
wget http://file.ofs.com/hv/bootloader.bin /download/bootloader.bin
fal probe bootloader
fal erase 0 0x40000
fal write 0 /download/bootloader.bin
+5
View File
@@ -0,0 +1,5 @@
rm /download/firmware.bin
wget http://file.ofs.com/hv/hv_firmware.bin /download/firmware.bin
fal probe ota
fal erase 0 0xC0000
fal write 0 /download/firmware.bin
+69
View File
@@ -0,0 +1,69 @@
import sys
import time
import _thread
import json
import gc
from script.umodbus.serial import ModbusRTU
uart_id = 4
slave_addr = 10 # address on bus as client
client = ModbusRTU(
addr=slave_addr, # address on bus
baudrate=115200, # optional, default 9600
# data_bits=8, # optional, default 8
# stop_bits=1, # optional, default 1
# parity=None, # optional, default None
# ctrl_pin=12, # optional, control DE/RE
uart_id=uart_id # optional, default 1, see port specific documentation
)
register_definitions = {
"COILS": {
"control": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
}
},
"HREGS": {
"params": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
}
},
"ISTS": {
"status": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
},
"IREGS": {
"input": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
}
}
# use the defined values of each register type provided by register_definitions
client.setup_registers(registers=register_definitions)
print(client)
while True:
try:
result = client.process()
except KeyboardInterrupt:
print('KeyboardInterrupt, stopping RTU client...')
break
except Exception as e:
print('Exception during execution: {}'.format(e))
+3
View File
@@ -0,0 +1,3 @@
fal probe ota
fal erase 0 0xC0000
fal write 0 /download/firmware.bin
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from .version import __version__
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
import struct
# custom packages
from . import const as Const
from . import functions
# typing not natively supported on MicroPython
from .typing import List, Optional, Tuple, Union
class Request(object):
"""Deconstruct request data received via TCP or Serial"""
def __init__(self, interface, data: bytearray) -> None:
self._itf = interface
self.unit_addr = data[0]
self.function, self.register_addr = struct.unpack_from('>BH', data, 1)
if self.function in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x07D0:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = None
elif self.function in [Const.READ_HOLDING_REGISTERS, Const.READ_INPUT_REGISTER]:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x007D:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = None
elif self.function == Const.WRITE_SINGLE_COIL:
self.quantity = None
self.data = data[4:6]
# allowed values: 0x0000 or 0xFF00
if (self.data[0] not in [0x00, 0xFF]) or self.data[1] != 0x00:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
elif self.function == Const.WRITE_SINGLE_REGISTER:
self.quantity = None
self.data = data[4:6]
# all values allowed
elif self.function == Const.WRITE_MULTIPLE_COILS:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x07D0:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = data[7:]
if len(self.data) != ((self.quantity - 1) // 8) + 1:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
elif self.function == Const.WRITE_MULTIPLE_REGISTERS:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x007B:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = data[7:]
if len(self.data) != self.quantity * 2:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
else:
# Not implemented functions
self.quantity = None
self.data = data[4:]
def send_response(self,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response via the configured interface.
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed values are used
:type signed: bool
"""
self._itf.send_response(self.unit_addr,
self.function,
self.register_addr,
self.quantity,
self.data,
values,
signed)
def send_exception(self, exception_code: int) -> None:
"""
Send an exception response.
:param exception_code: The exception code
:type exception_code: int
"""
self._itf.send_exception_response(self.unit_addr,
self.function,
exception_code)
class ModbusException(Exception):
"""Exception for signaling modbus errors"""
def __init__(self, function_code: int, exception_code: int) -> None:
self.function_code = function_code
self.exception_code = exception_code
class CommonModbusFunctions(object):
"""Common Modbus functions"""
def __init__(self):
pass
def read_coils(self,
slave_addr: int,
starting_addr: int,
coil_qty: int) -> List[bool]:
"""
Read coils (COILS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The coil starting address
:type starting_addr: int
:param coil_qty: The amount of coils to read
:type coil_qty: int
:returns: State of read coils as list
:rtype: List[bool]
"""
modbus_pdu = functions.read_coils(starting_address=starting_addr,
quantity=coil_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
status_pdu = functions.bytes_to_bool(byte_list=response,
bit_qty=coil_qty)
return status_pdu
def read_discrete_inputs(self,
slave_addr: int,
starting_addr: int,
input_qty: int) -> List[bool]:
"""
Read discrete inputs (ISTS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The discrete input starting address
:type starting_addr: int
:param input_qty: The amount of discrete inputs to read
:type input_qty: int
:returns: State of read discrete inputs as list
:rtype: List[bool]
"""
modbus_pdu = functions.read_discrete_inputs(
starting_address=starting_addr,
quantity=input_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
status_pdu = functions.bytes_to_bool(byte_list=response,
bit_qty=input_qty)
return status_pdu
def read_holding_registers(self,
slave_addr: int,
starting_addr: int,
register_qty: int,
signed: bool = True) -> Tuple[int, ...]:
"""
Read holding registers (HREGS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The holding register starting address
:type starting_addr: int
:param register_qty: The amount of holding registers to read
:type register_qty: int
:param signed: Indicates if signed
:type signed: bool
:returns: State of read holding register as tuple
:rtype: Tuple[int, ...]
"""
modbus_pdu = functions.read_holding_registers(
starting_address=starting_addr,
quantity=register_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
register_value = functions.to_short(byte_array=response, signed=signed)
return register_value
def read_input_registers(self,
slave_addr: int,
starting_addr: int,
register_qty: int,
signed: bool = True) -> Tuple[int, ...]:
"""
Read input registers (IREGS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The input register starting address
:type starting_addr: int
:param register_qty: The amount of input registers to read
:type register_qty: int
:param signed: Indicates if signed
:type signed: bool
:returns: State of read input register as tuple
:rtype: Tuple[int, ...]
"""
modbus_pdu = functions.read_input_registers(
starting_address=starting_addr,
quantity=register_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
register_value = functions.to_short(byte_array=response, signed=signed)
return register_value
def write_single_coil(self,
slave_addr: int,
output_address: int,
output_value: Union[int, bool]) -> bool:
"""
Update a single coil.
:param slave_addr: The slave address
:type slave_addr: int
:param output_address: The output address
:type output_address: int
:param output_value: The output value
:type output_value: Union[int, bool]
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_single_coil(output_address=output_address,
output_value=output_value)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_SINGLE_COIL,
address=output_address,
value=output_value,
signed=False)
return operation_status
def write_single_register(self,
slave_addr: int,
register_address: int,
register_value: int,
signed: bool = True) -> bool:
"""
Update a single register.
:param slave_addr: The slave address
:type slave_addr: int
:param register_address: The register address
:type register_address: int
:param register_value: The register value
:type register_value: int
:param signed: Indicates if signed
:type signed: bool
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_single_register(
register_address=register_address,
register_value=register_value,
signed=signed)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_SINGLE_REGISTER,
address=register_address,
value=register_value,
signed=signed)
return operation_status
def write_multiple_coils(self,
slave_addr: int,
starting_address: int,
output_values: List[Union[int, bool]]) -> bool:
"""
Update multiple coils.
:param slave_addr: The slave address
:type slave_addr: int
:param starting_address: The address of the first coil
:type starting_address: int
:param output_values: The output values
:type output_values: List[Union[int, bool]]
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_multiple_coils(
starting_address=starting_address,
value_list=output_values)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_MULTIPLE_COILS,
address=starting_address,
quantity=len(output_values))
return operation_status
def write_multiple_registers(self,
slave_addr: int,
starting_address: int,
register_values: List[int],
signed: bool = True) -> bool:
"""
Update multiple registers.
:param slave_addr: The slave address
:type slave_addr: int
:param starting_address: The starting address
:type starting_address: int
:param register_values: The register values
:type register_values: List[int]
:param signed: Indicates if signed
:type signed: bool
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_multiple_registers(
starting_address=starting_address,
register_values=register_values,
signed=signed)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_MULTIPLE_REGISTERS,
address=starting_address,
quantity=len(register_values),
signed=signed
)
return operation_status
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# Description summary taken from
# https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf
from micropython import const
# function codes
# defined as const(), see https://github.com/micropython/micropython/issues/573
#: Read contiguous status of coils
READ_COILS = const(0x01) # COILS, [0, 1]
#: Read contiguous status of discrete inputs
READ_DISCRETE_INPUTS = const(0x02) # ISTS, [0, 1]
#: Read the contents of a contiguous block of holding registers
READ_HOLDING_REGISTERS = const(0x03) # HREGS, [0, 65535]
#: Read contiguous input registers
READ_INPUT_REGISTER = const(0x04) # IREGS, [0, 65535]
#: Write a single coil output status to ON or OFF
WRITE_SINGLE_COIL = const(0x05) # COILS, [0, 1]
#: Write a single holding register
WRITE_SINGLE_REGISTER = const(0x06) # HREGS, [0, 65535]
#: Force each coil in a sequence of coils to either ON or OFF
WRITE_MULTIPLE_COILS = const(0x0F) # COILS, [0, 1]
#: Write a block of contiguous registers
WRITE_MULTIPLE_REGISTERS = const(0x10) # HREGS, [0, 65535]
"""
Modify the contents of a specified holding register using a combination of an
AND mask, an OR mask, and the register's current contents
"""
MASK_WRITE_REGISTER = const(0x16)
"""
Perform a combination of one read operation and one write operation in a
single MODBUS transaction
"""
READ_WRITE_MULTIPLE_REGISTERS = const(0x17)
#: Read the contents of a First-In-First-Out (FIFO) queue of register
READ_FIFO_QUEUE = const(0x18)
#: Perform a file record read
READ_FILE_RECORD = const(0x14)
#: Perform a file record write
WRITE_FILE_RECORD = const(0x15)
#: Read the contents of eight Exception Status outputs
READ_EXCEPTION_STATUS = const(0x07)
#: Provide series of tests for checking the communication system (serial only)
DIAGNOSTICS = const(0x08)
#: Get status word and an event count from the remote device com event counter
GET_COM_EVENT_COUNTER = const(0x0B)
#: Get a status word, event count, message count, and a field of event bytes
GET_COM_EVENT_LOG = const(0x0C)
#: Read the description of the type, the current status, and other informations
REPORT_SERVER_ID = const(0x11)
#: Encapsulated Interface Transport
READ_DEVICE_IDENTIFICATION = const(0x2B)
# exception codes
#: Function code received in query is not an allowable action for the server
ILLEGAL_FUNCTION = const(0x01)
#: Data address received in query is not an allowable address for the server
ILLEGAL_DATA_ADDRESS = const(0x02)
#: A value contained in the query is not an allowable value for the server
ILLEGAL_DATA_VALUE = const(0x03)
"""
An unrecoverable error occurred while the server was attempting to perform the
requested action
"""
SERVER_DEVICE_FAILURE = const(0x04)
#: Response is returned to prevent a timeout error from occurring in the client
ACKNOWLEDGE = const(0x05)
#: Server is engaged in processing a long duration program command
SERVER_DEVICE_BUSY = const(0x06)
#: Server attempted to read record file, but detected a parity error in memory
MEMORY_PARITY_ERROR = const(0x08)
"""
Gateway was unable to allocate an internal communication path from the input
port to the output port for processing the request
"""
GATEWAY_PATH_UNAVAILABLE = const(0x0A)
#: No response was obtained from the target device
DEVICE_FAILED_TO_RESPOND = const(0x0B)
# Protocol Data Unit (PDU) constants
#: CRC length
CRC_LENGTH = const(0x02)
#: Error code offset
ERROR_BIAS = const(0x80)
#: High Data Response length
RESPONSE_HDR_LENGTH = const(0x02)
#: Error response length
ERROR_RESP_LEN = const(0x05)
#: Fixed response length
FIXED_RESP_LEN = const(0x08)
#: Modbus Application Protocol High Data Response length
MBAP_HDR_LENGTH = const(0x07)
#: CRC16 lookup table
CRC16_TABLE = (
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601,
0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0,
0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81,
0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941,
0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01,
0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0,
0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081,
0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00,
0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0,
0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981,
0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700,
0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0,
0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281,
0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01,
0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1,
0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80,
0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541,
0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101,
0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0,
0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481,
0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801,
0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1,
0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581,
0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
0x4100, 0x81C1, 0x8081, 0x4040
)
# Code to generate the CRC-16 lookup table:
# def generate_crc16_table():
# crc_table = []
# for byte in range(256):
# crc = 0x0000
# for _ in range(8):
# if (byte ^ crc) & 0x0001:
# crc = (crc >> 1) ^ 0xa001
# else:
# crc >>= 1
# byte >>= 1
# crc_table.append(crc)
# return crc_table
+459
View File
@@ -0,0 +1,459 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
import struct
# custom packages
from . import const as Const
# typing not natively supported on MicroPython
from .typing import List, Optional, Union
def read_coils(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading coils.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 2000):
raise ValueError('Invalid number of coils')
return struct.pack('>BHH', Const.READ_COILS, starting_address, quantity)
def read_discrete_inputs(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading discrete inputs.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 2000):
raise ValueError('Invalid number of discrete inputs')
return struct.pack('>BHH',
Const.READ_DISCRETE_INPUTS,
starting_address,
quantity)
def read_holding_registers(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading holding registers.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 125):
raise ValueError('Invalid number of holding registers')
return struct.pack('>BHH',
Const.READ_HOLDING_REGISTERS,
starting_address,
quantity)
def read_input_registers(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading input registers.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 125):
raise ValueError('Invalid number of input registers')
return struct.pack('>BHH',
Const.READ_INPUT_REGISTER,
starting_address,
quantity)
def write_single_coil(output_address: int,
output_value: Union[int, bool]) -> bytes:
"""
Create Modbus message to update single coil
:param output_address: The output address
:type output_address: int
:param output_value: The output value
:type output_value: Union[int, bool]
:returns: Packed Modbus message
:rtype: bytes
"""
if output_value not in [0x0000, 0xFF00, False, True, 0, 1]:
raise ValueError('Illegal coil value')
if output_value not in [0x0000, 0xFF00]:
if output_value:
output_value = 0xFF00
else:
output_value = 0x0000
return struct.pack('>BHH',
Const.WRITE_SINGLE_COIL,
output_address,
output_value)
def write_single_register(register_address: int,
register_value: int,
signed: bool = True) -> bytes:
"""
Create Modbus message to writes a single register
:param register_address: The register address
:type register_address: int
:param register_value: The register value
:type register_value: int
:param signed: Flag whether data is signed or not
:type signed: bool
:returns: Packed Modbus message
:rtype: bytes
"""
fmt = 'h' if signed else 'H'
return struct.pack('>BH' + fmt,
Const.WRITE_SINGLE_REGISTER,
register_address,
register_value)
def write_multiple_coils(starting_address: int,
value_list: List[Union[int, bool]]) -> bytes:
"""
Create Modbus message to update multiple coils
:param starting_address: The starting address
:type starting_address: int
:param value_list: The list of output values
:type value_list: List[Union[int, bool]]
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= len(value_list) <= 0x07B0):
raise ValueError('Invalid quantity of outputs')
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
output_value = []
for index, byte in enumerate(sectioned_list):
# see https://github.com/brainelectronics/micropython-modbus/issues/22
# output = sum(v << i for i, v in enumerate(byte))
output = 0
for bit in byte:
output = (output << 1) | bit
output_value.append(output)
fmt = 'B' * len(output_value)
quantity = len(value_list)
byte_count = quantity // 8
if quantity % 8:
byte_count += 1
return struct.pack('>BHHB' + fmt,
Const.WRITE_MULTIPLE_COILS,
starting_address,
quantity,
byte_count,
*output_value)
def write_multiple_registers(starting_address: int,
register_values: List[int],
signed: bool = True) -> bytes:
"""
Create Modbus message to update multiple coils
:param starting_address: The starting address
:type starting_address: int
:param register_values: The list of output value
:type register_values: List[int, bool]
:param signed: Flag whether data is signed or not
:type signed: bool
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= len(register_values) <= 123):
raise ValueError('Invalid number of registers')
quantity = len(register_values)
byte_count = quantity * 2
fmt = ('h' if signed else 'H') * quantity
return struct.pack('>BHHB' + fmt,
Const.WRITE_MULTIPLE_REGISTERS,
starting_address,
quantity,
byte_count,
*register_values)
def validate_resp_data(data: bytes,
function_code: int,
address: int,
value: int = None,
quantity: int = None,
signed: bool = True) -> bool:
"""
Validate the response data.
:param data: The data
:type data: bytes
:param function_code: The function code
:type function_code: int
:param address: The address
:type address: int
:param value: The value
:type value: int
:param quantity: The quantity
:type quantity: int
:param signed: Indicates if signed
:type signed: bool
:returns: True if valid, False otherwise
:rtype: bool
"""
fmt = '>H' + ('h' if signed else 'H')
if function_code in [Const.WRITE_SINGLE_COIL, Const.WRITE_SINGLE_REGISTER]:
resp_addr, resp_value = struct.unpack(fmt, data)
# if bool(True) or int(1) is used as "output_value" of
# "write_single_coil" it will be internally converted to int(0xFF00),
# see Modbus specification, which is actually int(65280).
# Due to the non binary, but real value comparison of "value" and
# "resp_value", it would never match without the next two lines
# see #21
if function_code == Const.WRITE_SINGLE_COIL:
resp_value = bool(resp_value)
value = bool(value)
if (address == resp_addr) and (value == resp_value):
return True
elif function_code in [Const.WRITE_MULTIPLE_COILS,
Const.WRITE_MULTIPLE_REGISTERS]:
resp_addr, resp_qty = struct.unpack(fmt, data)
if (address == resp_addr) and (quantity == resp_qty):
return True
return False
def response(function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
value_list: Optional[list] = None,
signed: bool = True) -> bytes:
"""
Construct a Modbus response Protocol Data Unit
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param value_list: The values
:type value_list: Optional[list]
:param signed: Indicates if signed
:type signed: bool
:returns: Protocol data unit
:rtype: bytes
"""
if function_code in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
output_value = []
for index, byte in enumerate(sectioned_list):
output = 0
for i, bit in enumerate(byte):
output |= bit << i
output_value.append(output)
fmt = 'B' * len(output_value)
return struct.pack('>BB' + fmt,
function_code,
((len(value_list) - 1) // 8) + 1,
*output_value)
elif function_code in [Const.READ_HOLDING_REGISTERS,
Const.READ_INPUT_REGISTER]:
quantity = len(value_list)
if not (0x0001 <= quantity <= 0x007D):
raise ValueError('invalid number of registers')
if signed is True or signed is False:
fmt = ('h' if signed else 'H') * quantity
else:
fmt = ''
for s in signed:
fmt += 'h' if s else 'H'
return struct.pack('>BB' + fmt,
function_code,
quantity * 2,
*value_list)
elif function_code in [Const.WRITE_SINGLE_COIL,
Const.WRITE_SINGLE_REGISTER]:
return struct.pack('>BHBB',
function_code,
request_register_addr,
*request_data)
elif function_code in [Const.WRITE_MULTIPLE_COILS,
Const.WRITE_MULTIPLE_REGISTERS]:
return struct.pack('>BHH',
function_code,
request_register_addr,
request_register_qty)
def exception_response(function_code: int, exception_code: int) -> bytes:
"""
Create Modbus exception response
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
:returns: Packed Modbus message
:rtype: bytes
"""
return struct.pack('>BB', Const.ERROR_BIAS + function_code, exception_code)
def bytes_to_bool(byte_list: bytes, bit_qty: Optional[int] = 1) -> List[bool]:
"""
Convert bytes to list of boolean values
:param byte_list: The byte list
:type byte_list: bytes
:param bit_qty: Amount of bits received
:type bit_qty: Optional[int]
:returns: Boolean representation
:rtype: List[bool]
"""
bool_list = []
for index, byte in enumerate(byte_list):
this_qty = bit_qty
if this_qty >= 8:
this_qty = 8
# evil hack for missing keyword support in MicroPython format()
fmt = '{:0' + str(this_qty) + 'b}'
binary_str = fmt.format(byte)
bool_list.extend([bool(int(binary_str[i])) for i in range(len(binary_str)-1, -1, -1)])
bit_qty -= 8
return bool_list
def to_short(byte_array: bytes, signed: bool = True) -> bytes:
"""
Convert bytes to tuple of integer values
:param byte_array: The byte array
:type byte_array: bytes
:param signed: Indicates if signed
:type signed: bool
:returns: Integer representation
:rtype: bytes
"""
response_quantity = int(len(byte_array) / 2)
fmt = '>' + (('h' if signed else 'H') * response_quantity)
return struct.unpack(fmt, byte_array)
def float_to_bin(num: float) -> bin:
"""
Convert floating point value to binary
See IEEE 754
:param num: The number
:type num: float
:returns: Binary representation
:rtype: bin
"""
# no "zfill" available in MicroPython
# return bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:].zfill(32)
return '{:0>{w}}'.format(
bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:],
w=32)
def bin_to_float(binary: str) -> float:
"""
Convert binary string to floating point value
:param binary: The binary string
:type binary: str
:returns: Converted floating point value
:rtype: float
"""
return struct.unpack('!f', struct.pack('!I', int(binary, 2)))[0]
def int_to_bin(num: int) -> str:
"""
Convert integer to binary
:param num: The number
:type num: int
:returns: Binary representation of given input
:rtype: str
"""
return "{0:b}".format(num)
+873
View File
@@ -0,0 +1,873 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Modbus register abstraction class
Used to add, remove, set and get values or states of a register or coil.
Additional helper properties and functions like getters for changed registers
are available as well.
This class is inherited by the Modbus client implementations
:py:class:`umodbus.serial.ModbusRTU` and :py:class:`umodbus.tcp.ModbusTCP`
"""
# system packages
import time
# custom packages
from . import functions
from . import const as Const
from .common import Request
# typing not natively supported on MicroPython
from .typing import Callable, dict_keys, List, Optional, Union
class Modbus(object):
"""
Modbus register abstraction
:param itf: Abstraction interface
:type itf: Callable
:param addr_list: List of addresses
:type addr_list: List[int]
"""
def __init__(self, itf, addr_list: List[int]) -> None:
self._itf = itf
self._addr_list = addr_list
# modbus register types with their default value
self._available_register_types = ['COILS', 'HREGS', 'IREGS', 'ISTS']
self._register_dict = dict()
for reg_type in self._available_register_types:
self._register_dict[reg_type] = dict()
self._default_vals = dict(zip(self._available_register_types,
[False, 0, 0, False]))
# registers which can be set by remote device
self._changeable_register_types = ['COILS', 'HREGS']
self._changed_registers = dict()
for reg_type in self._changeable_register_types:
self._changed_registers[reg_type] = dict()
def process(self) -> bool:
"""
Process the Modbus requests.
:returns: Result of processing, True on success, False otherwise
:rtype: bool
"""
reg_type = None
req_type = None
request = self._itf.get_request(unit_addr_list=self._addr_list,
timeout=0)
if request is None:
return False
if request.function == Const.READ_COILS:
# Coils (setter+getter) [0, 1]
# function 01 - read single register
reg_type = 'COILS'
req_type = 'READ'
elif request.function == Const.READ_DISCRETE_INPUTS:
# Ists (only getter) [0, 1]
# function 02 - read input status (discrete inputs/digital input)
reg_type = 'ISTS'
req_type = 'READ'
elif request.function == Const.READ_HOLDING_REGISTERS:
# Hregs (setter+getter) [0, 65535]
# function 03 - read holding register
reg_type = 'HREGS'
req_type = 'READ'
elif request.function == Const.READ_INPUT_REGISTER:
# Iregs (only getter) [0, 65535]
# function 04 - read input registers
reg_type = 'IREGS'
req_type = 'READ'
elif (request.function == Const.WRITE_SINGLE_COIL or
request.function == Const.WRITE_MULTIPLE_COILS):
# Coils (setter+getter) [0, 1]
# function 05 - write single coil
# function 15 - write multiple coil
reg_type = 'COILS'
req_type = 'WRITE'
elif (request.function == Const.WRITE_SINGLE_REGISTER or
request.function == Const.WRITE_MULTIPLE_REGISTERS):
# Hregs (setter+getter) [0, 65535]
# function 06 - write holding register
# function 16 - write multiple holding register
reg_type = 'HREGS'
req_type = 'WRITE'
else:
request.send_exception(Const.ILLEGAL_FUNCTION)
if reg_type:
if req_type == 'READ':
self._process_read_access(request=request, reg_type=reg_type)
elif req_type == 'WRITE':
self._process_write_access(request=request, reg_type=reg_type)
return True
def _create_response(self,
request: Request,
reg_type: str) -> Union[List[bool], List[int]]:
"""
Create a response.
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
:returns: Values of this register
:rtype: Union[List[bool], List[int]]
"""
data = []
default_value = {'val': 0}
reg_dict = self._register_dict[reg_type]
if reg_type in ['COILS', 'ISTS']:
default_value = {'val': False}
for addr in range(request.register_addr,
request.register_addr + request.quantity):
value = reg_dict.get(addr, default_value)['val']
if isinstance(value, (list, tuple)):
data.extend(value)
else:
data.append(value)
# caution LSB vs MSB
# [
# 1, 0, 1, 1, 0, 0, 1, 1, # 0xB3
# 1, 1, 0, 1, 0, 1, 1, 0, # 0xD6
# 1, 0, 1 # 0x5
# ]
# but should be, documented at #38, see
# https://github.com/brainelectronics/micropython-modbus/issues/38
# this is only an issue of data provisioning as client/slave,
# it has thereby NOT to be fixed in
# :py:function:`umodbus.functions.bytes_to_bool`
# [
# 1, 1, 0, 0, 1, 1, 0, 1, # 0xCD
# 0, 1, 1, 0, 1, 0, 1, 1, # 0x6B
# 1, 0, 1 # 0x5
# ]
# 27 .... 20
# CD 1100 1101
#
# 35 .... 28
# 6B 0110 1011
#
# 43 .... 36
# 05 0000 0101
#
# 1011 0011 1101 0110 1010 0000
return data
def _process_read_access(self, request: Request, reg_type: str) -> None:
"""
Process read access to register
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
"""
address = request.register_addr
if address in self._register_dict[reg_type]:
if self._register_dict[reg_type][address].get('on_get_cb', 0):
vals = self._create_response(request=request,
reg_type=reg_type)
_cb = self._register_dict[reg_type][address]['on_get_cb']
_cb(reg_type=reg_type, address=address, val=vals)
vals = self._create_response(request=request, reg_type=reg_type)
request.send_response(vals)
else:
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
def _process_write_access(self, request: Request, reg_type: str) -> None:
"""
Process write access to register
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
"""
address = request.register_addr
val = 0
valid_register = False
if address in self._register_dict[reg_type]:
if request.data is None:
request.send_exception(Const.ILLEGAL_DATA_VALUE)
return
if reg_type == 'COILS':
valid_register = True
if request.function == Const.WRITE_SINGLE_COIL:
val = request.data[0]
if 0x00 < val < 0xFF:
valid_register = False
request.send_exception(Const.ILLEGAL_DATA_VALUE)
else:
val = [(val == 0xFF)]
elif request.function == Const.WRITE_MULTIPLE_COILS:
tmp = int.from_bytes(request.data, "big")
val = [
bool(tmp & (1 << n)) for n in range(request.quantity)
]
if valid_register:
self.set_coil(address=address, value=val)
elif reg_type == 'HREGS':
valid_register = True
val = list(functions.to_short(byte_array=request.data,
signed=False))
if request.function in [Const.WRITE_SINGLE_REGISTER,
Const.WRITE_MULTIPLE_REGISTERS]:
self.set_hreg(address=address, value=val)
else:
# nothing except holding registers or coils can be set
request.send_exception(Const.ILLEGAL_FUNCTION)
if valid_register:
request.send_response()
self._set_changed_register(reg_type=reg_type,
address=address,
value=val)
if self._register_dict[reg_type][address].get('on_set_cb', 0):
_cb = self._register_dict[reg_type][address]['on_set_cb']
_cb(reg_type=reg_type, address=address, val=val)
else:
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
def add_coil(self,
address: int,
value: Union[bool, List[bool]] = False,
on_set_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add a coil to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[bool, List[bool]], optional
:param on_set_cb: Callback on setting the coil
:type on_set_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the coil
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='COILS',
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def remove_coil(self, address: int) -> Union[None, bool, List[bool]]:
"""
Remove a coil from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, List[bool]]
"""
return self._remove_reg_from_dict(reg_type='COILS', address=address)
def set_coil(self,
address: int,
value: Union[bool, List[bool]] = False) -> None:
"""
Set the coil value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[bool, List[bool]], optional
"""
self._set_reg_in_dict(reg_type='COILS',
address=address,
value=value)
def get_coil(self, address: int) -> Union[bool, List[bool]]:
"""
Get the coil value.
:param address: The address (ID) of the register
:type address: bool
:returns: Coil value
:rtype: Union[bool, List[bool]]
"""
return self._get_reg_in_dict(reg_type='COILS',
address=address)
@property
def coils(self) -> dict_keys:
"""
Get the configured coils.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='COILS')
def add_hreg(self,
address: int,
value: Union[int, List[int]] = 0,
on_set_cb: Callable[[str, int, List[int]], None] = None,
on_get_cb: Callable[[str, int, List[int]], None] = None) -> None:
"""
Add a holding register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
:param on_set_cb: Callback on setting the holding register
:type on_set_cb: Callable[[str, int, List[int]], None]
:param on_get_cb: Callback on getting the holding register
:type on_get_cb: Callable[[str, int, List[int]], None]
"""
self._set_reg_in_dict(reg_type='HREGS',
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def remove_hreg(self, address: int) -> Union[None, int, List[int]]:
"""
Remove a holding register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, int, List[int]]
"""
return self._remove_reg_from_dict(reg_type='HREGS', address=address)
def set_hreg(self, address: int, value: Union[int, List[int]] = 0) -> None:
"""
Set the holding register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: int or list of int, optional
"""
self._set_reg_in_dict(reg_type='HREGS',
address=address,
value=value)
def get_hreg(self, address: int) -> Union[int, List[int]]:
"""
Get the holding register value.
:param address: The address (ID) of the register
:type address: int
:returns: Holding register value
:rtype: Union[int, List[int]]
"""
return self._get_reg_in_dict(reg_type='HREGS',
address=address)
@property
def hregs(self) -> dict_keys:
"""
Get the configured holding registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='HREGS')
def add_ist(self,
address: int,
value: Union[bool, List[bool]] = False,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add a discrete input register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: bool or list of bool, optional
:param on_get_cb: Callback on getting the discrete input register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='ISTS',
address=address,
value=value,
on_get_cb=on_get_cb)
def remove_ist(self, address: int) -> Union[None, bool, List[bool]]:
"""
Remove a discrete input register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, List[bool]]
"""
return self._remove_reg_from_dict(reg_type='ISTS', address=address)
def set_ist(self, address: int, value: bool = False) -> None:
"""
Set the discrete input register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: bool or list of bool, optional
"""
self._set_reg_in_dict(reg_type='ISTS',
address=address,
value=value)
def get_ist(self, address: int) -> Union[bool, List[bool]]:
"""
Get the discrete input register value.
:param address: The address (ID) of the register
:type address: int
:returns: Discrete input register value
:rtype: Union[bool, List[bool]]
"""
return self._get_reg_in_dict(reg_type='ISTS',
address=address)
@property
def ists(self) -> dict_keys:
"""
Get the configured discrete input registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='ISTS')
def add_ireg(self,
address: int,
value: Union[int, List[int]] = 0,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add an input register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
:param on_get_cb: Callback on getting the input register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='IREGS',
address=address,
value=value,
on_get_cb=on_get_cb)
def remove_ireg(self, address: int) -> Union[None, int, List[int]]:
"""
Remove an input register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, int, List[int]]
"""
return self._remove_reg_from_dict(reg_type='IREGS', address=address)
def set_ireg(self, address: int, value: Union[int, List[int]] = 0) -> None:
"""
Set the input register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
"""
self._set_reg_in_dict(reg_type='IREGS',
address=address,
value=value)
def get_ireg(self, address: int) -> Union[int, List[int]]:
"""
Get the input register value.
:param address: The address (ID) of the register
:type address: int
:returns: Input register value
:rtype: Union[int, List[int]]
"""
return self._get_reg_in_dict(reg_type='IREGS',
address=address)
@property
def iregs(self) -> dict_keys:
"""
Get the configured input registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='IREGS')
def _set_reg_in_dict(self,
reg_type: str,
address: int,
value: Union[bool, int, List[bool], List[int]],
on_set_cb: Callable[[str, int, Union[List[bool],
List[int]]],
None] = None,
on_get_cb: Callable[[str, int, Union[List[bool],
List[int]]],
None] = None) -> None:
"""
Set the register value in the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value(s) of the register(s)
:type value: Union[bool, int, List[bool], List[int]]
:param on_set_cb: Callback on setting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:raise KeyError: No register at specified address found
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
if isinstance(value, (list, tuple)):
# flatten the list and add single registers only
for idx, val in enumerate(value):
this_addr = address + idx
self._set_single_reg_in_dict(reg_type=reg_type,
address=this_addr,
value=val,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
else:
self._set_single_reg_in_dict(reg_type=reg_type,
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def _set_single_reg_in_dict(self,
reg_type: str,
address: int,
value: Union[bool, int],
on_set_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
] = None,
on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
] = None) -> None:
"""
Set a register value in the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value of the register
:type value: Union[bool, int]
:param on_set_cb: Callback on setting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
data = {'val': value}
# if the register exists already in the register dict a "set_*"
# function might have called this functions
if address in self._register_dict[reg_type]:
# try to get the (already) registered callback function from the
# register dict of this address with the this time call function
# parameter callback value as fallback
on_set_cb = self._register_dict[reg_type][address].get('on_set_cb',
on_set_cb)
on_get_cb = self._register_dict[reg_type][address].get('on_get_cb',
on_get_cb)
if callable(on_set_cb):
data['on_set_cb'] = on_set_cb
if callable(on_get_cb):
data['on_get_cb'] = on_get_cb
self._register_dict[reg_type][address] = data
def _remove_reg_from_dict(self,
reg_type: str,
address: int) -> Union[None, bool, int, List[bool], List[int]]:
"""
Remove the register from the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:raise KeyError: No register at specified address found
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, int, List[bool], List[int]]
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
return self._register_dict[reg_type].pop(address, None)
def _get_reg_in_dict(self,
reg_type: str,
address: int) -> Union[bool, int, List[bool], List[int]]:
"""
Get the register value from the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:raise KeyError: No register at specified address found
:returns: Register value
:rtype: Union[bool, int, List[bool], List[int]]
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
if address in self._register_dict[reg_type]:
return self._register_dict[reg_type][address]['val']
else:
raise KeyError('No {} available for the register address {}'.
format(reg_type, address))
def _get_regs_of_dict(self, reg_type: str) -> dict_keys:
"""
Get all configured registers of specified register type.
:param reg_type: The register type
:type reg_type: str
:raise KeyError: No register at specified address found
:returns: The configured registers of the specified register type.
:rtype: dict_keys
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
return self._register_dict[reg_type].keys()
def _check_valid_register(self, reg_type: str) -> bool:
"""
Check register type to be a valid modbus register
:param reg_type: The register type
:type reg_type: str
:returns: Flag whether register type is valid
:rtype: bool
"""
if reg_type in self._available_register_types:
return True
else:
return False
@property
def changed_registers(self) -> dict:
"""
Get the changed registers.
:returns: The changed registers.
:rtype: dict
"""
return self._changed_registers
@property
def changed_coils(self) -> dict:
"""
Get the changed coil registers.
:returns: The changed coil registers.
:rtype: dict
"""
return self._changed_registers['COILS']
@property
def changed_hregs(self) -> dict:
"""
Get the changed holding registers.
:returns: The changed holding registers.
:rtype: dict
"""
return self._changed_registers['HREGS']
def _set_changed_register(self,
reg_type: str,
address: int,
value: Union[bool, int, List[bool], List[int]]) -> None:
"""
Set the register value in the dictionary of changed registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value
:type value: Union[bool, int, List[bool], List[int]]
:raise KeyError: Register can not be changed externally
"""
if reg_type in self._changeable_register_types:
if isinstance(value, (list, tuple)):
for idx, val in enumerate(value):
content = {'val': val, 'time': time.ticks_ms()}
self._changed_registers[reg_type][address + idx] = content
else:
content = {'val': value, 'time': time.ticks_ms()}
self._changed_registers[reg_type][address] = content
else:
raise KeyError('{} can not be changed externally'.format(reg_type))
def _remove_changed_register(self,
reg_type: str,
address: int,
timestamp: int) -> bool:
"""
Remove the register from the dictionary of changed registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param timestamp: The timestamp of the change in milliseconds
:type timestamp: int
:raise KeyError: No register at specified address found
:returns: Result of removing register from dict
:rtype: bool
"""
result = False
if reg_type in self._changeable_register_types:
_changed_register_timestamp = self._changed_registers[reg_type][address]['time']
if _changed_register_timestamp == timestamp:
self._changed_registers[reg_type].pop(address, None)
result = True
else:
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._changeable_register_types))
return result
def setup_registers(self,
registers: dict = dict(),
use_default_vals: Optional[bool] = False) -> None:
"""
Setup all registers of the client
:param registers: The registers
:type registers: dict
:param use_default_vals: Flag to use dummy default values
:type use_default_vals: Optional[bool]
"""
if len(registers):
for reg_type, default_val in self._default_vals.items():
if reg_type in registers:
for reg, val in registers[reg_type].items():
address = val['register']
if use_default_vals:
if 'len' in val:
value = [default_val] * val['len']
else:
value = default_val
else:
value = val['val']
on_set_cb = val.get('on_set_cb', None)
on_get_cb = val.get('on_get_cb', None)
if reg_type == 'COILS':
self.add_coil(address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
elif reg_type == 'HREGS':
self.add_hreg(address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
elif reg_type == 'ISTS':
self.add_ist(address=address,
value=value,
on_get_cb=on_get_cb) # only getter
elif reg_type == 'IREGS':
self.add_ireg(address=address,
value=value,
on_get_cb=on_get_cb) # only getter
else:
# invalid register type
pass
else:
pass
+476
View File
@@ -0,0 +1,476 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
from machine import UART
from machine import Pin
import struct
import time
# custom packages
from . import const as Const
from . import functions
from .common import Request, CommonModbusFunctions
from .common import ModbusException
from .modbus import Modbus
# typing not natively supported on MicroPython
from .typing import List, Optional, Union
class ModbusRTU(Modbus):
"""
Modbus RTU client class
:param addr: The address of this device on the bus
:type addr: int
:param baudrate: The baudrate, default 9600
:type baudrate: int
:param data_bits: The data bits, default 8
:type data_bits: int
:param stop_bits: The stop bits, default 1
:type stop_bits: int
:param parity: The parity, default None
:type parity: Optional[int]
:param pins: The pins as list [TX, RX]
:type pins: List[Union[int, Pin], Union[int, Pin]]
:param ctrl_pin: The control pin
:type ctrl_pin: int
:param uart_id: The ID of the used UART
:type uart_id: int
"""
def __init__(self,
addr: int,
baudrate: int = 9600,
data_bits: int = 8,
stop_bits: int = 1,
parity: Optional[int] = None,
pins: List[Union[int, Pin], Union[int, Pin]] = None,
ctrl_pin: int = None,
uart_id: int = 1):
super().__init__(
# set itf to Serial object, addr_list to [addr]
Serial(uart_id=uart_id,
baudrate=baudrate,
data_bits=data_bits,
stop_bits=stop_bits,
parity=parity,
pins=pins,
ctrl_pin=ctrl_pin),
[addr]
)
class Serial(CommonModbusFunctions):
def __init__(self,
uart_id: int = 1,
baudrate: int = 9600,
data_bits: int = 8,
stop_bits: int = 1,
parity=None,
pins: List[Union[int, Pin], Union[int, Pin]] = None,
ctrl_pin: int = None):
"""
Setup Serial/RTU Modbus
:param uart_id: The ID of the used UART
:type uart_id: int
:param baudrate: The baudrate, default 9600
:type baudrate: int
:param data_bits: The data bits, default 8
:type data_bits: int
:param stop_bits: The stop bits, default 1
:type stop_bits: int
:param parity: The parity, default None
:type parity: Optional[int]
:param pins: The pins as list [TX, RX]
:type pins: List[Union[int, Pin], Union[int, Pin]]
:param ctrl_pin: The control pin
:type ctrl_pin: int
"""
# UART flush function is introduced in Micropython v1.20.0
self._has_uart_flush = callable(getattr(UART, "flush", None))
if ctrl_pin is not None and ctrl_pin < 0:
self._uart = UART(uart_id,
baudrate=baudrate,
bits=data_bits,
parity=parity,
stop=stop_bits,
# timeout_chars=2, # WiPy only
pins=pins, # WiPy only
flow=-ctrl_pin
)
ctrl_pin = None
else:
self._uart = UART(uart_id,
baudrate=baudrate,
bits=data_bits,
parity=parity,
stop=stop_bits,
# timeout_chars=2, # WiPy only
pins=pins # WiPy only
)
if ctrl_pin is not None:
self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
else:
self._ctrlPin = None
# timing of 1 character in microseconds (us)
self._t1char = (1000000 * (data_bits + stop_bits + 2)) // baudrate
# inter-frame delay in microseconds (us)
# - <= 19200 bps: 3.5x timing of 1 character
# - > 19200 bps: 1750 us
if baudrate <= 19200:
self._inter_frame_delay = (self._t1char * 3500) // 1000
else:
self._inter_frame_delay = 1750
def _calculate_crc16(self, data: bytearray) -> bytes:
"""
Calculates the CRC16.
:param data: The data
:type data: bytearray
:returns: The crc 16.
:rtype: bytes
"""
crc = 0xFFFF
for char in data:
crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]
return struct.pack('<H', crc)
def _exit_read(self, response: bytearray) -> bool:
"""
Return on modbus read error
:param response: The response
:type response: bytearray
:returns: State of basic read response evaluation,
True if entire response has been read
:rtype: bool
"""
response_len = len(response)
if response_len >= 2 and response[1] >= Const.ERROR_BIAS:
if response_len < Const.ERROR_RESP_LEN:
return False
elif response_len >= 3 and (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[2] + Const.CRC_LENGTH
if response_len < expected_len:
return False
elif response_len < Const.FIXED_RESP_LEN:
return False
return True
def _uart_read(self) -> bytearray:
"""
Read incoming slave response from UART
:returns: Read content
:rtype: bytearray
"""
response = bytearray()
# TODO: use some kind of hint or user-configurable delay
# to determine this loop counter
for x in range(1, 120):
rx = self._uart.read()
if rx is not None:
# WiPy only
# response.extend(self._uart.readall())
response.extend(rx)
# variable length function codes may require multiple reads
if self._exit_read(response):
break
# wait for the maximum time between two frames
time.sleep_us(self._inter_frame_delay)
return response
def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
"""
Read a Modbus frame
:param timeout: The timeout
:type timeout: Optional[int]
:returns: Received message
:rtype: bytearray
"""
received_bytes = bytearray()
if self._uart.any() <= 0:
return received_bytes
# set default timeout to at twice the inter-frame delay
if timeout == 0 or timeout is None:
timeout = 2 * self._inter_frame_delay # in microseconds
start_us = time.ticks_us()
#print(start_us)
# stay inside this while loop at least for the timeout time
while (time.ticks_diff(time.ticks_us(), start_us) <= timeout):
# check amount of available characters
if self._uart.any() > 0:
# remember this time in microseconds
last_byte_ts = time.ticks_us()
# do not stop reading and appending the result to the buffer
# until the time between two frames elapsed
while True:
# WiPy only
# r = self._uart.readall()
time.sleep_us(100)
r = self._uart.read()
# if something has been read after the first iteration of
# this inner while loop (within self._inter_frame_delay)
if r is not None and len(r) > 0:
# append the new read stuff to the buffer
received_bytes.extend(r)
# update the timestamp of the last byte being read
last_byte_ts = time.ticks_us()
#print(last_byte_ts, received_bytes)
if time.ticks_diff(time.ticks_us(), last_byte_ts) >= self._inter_frame_delay:
break
# if something has been read before the overall timeout is reached
if len(received_bytes) > 0:
#print(time.ticks_diff(time.ticks_us(), start_us))
return received_bytes
#print(time.ticks_diff(time.ticks_us(), start_us))
# return the result in case the overall timeout has been reached
return received_bytes
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
"""
Send Modbus frame via UART
If a flow control pin has been setup, it will be controlled accordingly
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
"""
# modbus_adu: Modbus Application Data Unit
# consists of the Modbus PDU, with slave address prepended and checksum appended
modbus_adu = bytearray()
modbus_adu.append(slave_addr)
modbus_adu.extend(modbus_pdu)
modbus_adu.extend(self._calculate_crc16(modbus_adu))
if self._ctrlPin:
self._ctrlPin.on()
# wait until the control pin really changed
# 85-95us (ESP32 @ 160/240MHz)
time.sleep_us(200)
# the timing of this part is critical:
# - if we disable output too early,
# the command will not be received in full
# - if we disable output too late,
# the incoming response will lose some data at the beginning
# easiest to just wait for the bytes to be sent out on the wire
send_start_time = time.ticks_us()
# 360-400us @ 9600-115200 baud (measured) (ESP32 @ 160/240MHz)
self._uart.write(modbus_adu)
send_finish_time = time.ticks_us()
if self._has_uart_flush:
self._uart.flush()
time.sleep_us(self._t1char)
else:
sleep_time_us = (
self._t1char * len(modbus_adu) - # total frame time in us
time.ticks_diff(send_finish_time, send_start_time) +
100 # only required at baudrates above 57600, but hey 100us
)
time.sleep_us(sleep_time_us)
if self._ctrlPin:
self._ctrlPin.off()
def _send_receive(self,
modbus_pdu: bytes,
slave_addr: int,
count: bool) -> bytes:
"""
Send a modbus message and receive the reponse.
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
:param count: The count
:type count: bool
:returns: Validated response content
:rtype: bytes
"""
# flush the Rx FIFO buffer
self._uart.read()
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
return self._validate_resp_hdr(response=self._uart_read(),
slave_addr=slave_addr,
function_code=modbus_pdu[0],
count=count)
def _validate_resp_hdr(self,
response: bytearray,
slave_addr: int,
function_code: int,
count: bool) -> bytes:
"""
Validate the response header.
:param response: The response
:type response: bytearray
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param count: The count
:type count: bool
:returns: Modbus response content
:rtype: bytes
"""
if len(response) == 0:
raise OSError('no data received from slave')
resp_crc = response[-Const.CRC_LENGTH:]
expected_crc = self._calculate_crc16(
response[0:len(response) - Const.CRC_LENGTH]
)
if ((resp_crc[0] is not expected_crc[0]) or
(resp_crc[1] is not expected_crc[1])):
raise OSError('invalid response CRC')
if (response[0] != slave_addr):
raise ValueError('wrong slave address')
if (response[1] == (function_code + Const.ERROR_BIAS)):
raise ValueError('slave returned exception code: {:d}'.
format(response[2]))
hdr_length = (Const.RESPONSE_HDR_LENGTH + 1) if count else \
Const.RESPONSE_HDR_LENGTH
return response[hdr_length:len(response) - Const.CRC_LENGTH]
def send_response(self,
slave_addr: int,
function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed
:type signed: bool
"""
modbus_pdu = functions.response(
function_code=function_code,
request_register_addr=request_register_addr,
request_register_qty=request_register_qty,
request_data=request_data,
value_list=values,
signed=signed
)
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
def send_exception_response(self,
slave_addr: int,
function_code: int,
exception_code: int) -> None:
"""
Send an exception response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
"""
modbus_pdu = functions.exception_response(
function_code=function_code,
exception_code=exception_code)
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
def get_request(self,
unit_addr_list: List[int],
timeout: Optional[int] = None) -> Union[Request, None]:
"""
Check for request within the specified timeout
:param unit_addr_list: The unit address list
:type unit_addr_list: Optional[list]
:param timeout: The timeout
:type timeout: Optional[int]
:returns: A request object or None.
:rtype: Union[Request, None]
"""
req = self._uart_read_frame(timeout=timeout)
if len(req) < 8:
return None
if req[0] not in unit_addr_list:
return None
req_crc = req[-Const.CRC_LENGTH:]
req_no_crc = req[:-Const.CRC_LENGTH]
expected_crc = self._calculate_crc16(req_no_crc)
if (req_crc[0] != expected_crc[0]) or (req_crc[1] != expected_crc[1]):
return None
try:
request = Request(interface=self, data=req_no_crc)
except ModbusException as e:
self.send_exception_response(
slave_addr=req[0],
function_code=e.function_code,
exception_code=e.exception_code)
return None
return request
+416
View File
@@ -0,0 +1,416 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
# import random
import struct
import socket
import time
# custom packages
from . import functions
from . import const as Const
from .common import Request, CommonModbusFunctions
from .common import ModbusException
from .modbus import Modbus
# typing not natively supported on MicroPython
from .typing import Optional, Tuple, Union
class ModbusTCP(Modbus):
"""Modbus TCP client class"""
def __init__(self):
super().__init__(
# set itf to TCPServer object, addr_list to None
TCPServer(),
None
)
def bind(self,
local_ip: str,
local_port: int = 502,
max_connections: int = 10) -> None:
"""
Bind IP and port for incomming requests
:param local_ip: IP of this device listening for requests
:type local_ip: str
:param local_port: Port of this device
:type local_port: int
:param max_connections: Number of maximum connections
:type max_connections: int
"""
self._itf.bind(local_ip, local_port, max_connections)
def get_bound_status(self) -> bool:
"""
Get the IP and port binding status.
:returns: The bound status, True if already bound, False otherwise.
:rtype: bool
"""
try:
return self._itf.get_is_bound()
except Exception:
return False
class TCP(CommonModbusFunctions):
"""
TCP class handling socket connections and parsing the Modbus data
:param slave_ip: IP of this device listening for requests
:type slave_ip: str
:param slave_port: Port of this device
:type slave_port: int
:param timeout: Socket timeout in seconds
:type timeout: float
"""
def __init__(self,
slave_ip: str,
slave_port: int = 502,
timeout: float = 5.0):
self._sock = socket.socket()
self.trans_id_ctr = 0
# print(socket.getaddrinfo(slave_ip, slave_port))
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
self._sock.connect(socket.getaddrinfo(slave_ip, slave_port)[0][-1])
self._sock.settimeout(timeout)
def _create_mbap_hdr(self,
slave_addr: int,
modbus_pdu: bytes) -> Tuple[bytes, int]:
"""
Create a Modbus header.
:param slave_addr: The slave identifier
:type slave_addr: int
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:returns: Modbus header and unique transaction ID
:rtype: Tuple[bytes, int]
"""
# only available on WiPy
# trans_id = machine.rng() & 0xFFFF
# use builtin function to generate random 24 bit integer
# trans_id = random.getrandbits(24) & 0xFFFF
# use incrementing counter as it's faster
trans_id = self.trans_id_ctr
self.trans_id_ctr += 1
mbap_hdr = struct.pack(
'>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_addr)
return mbap_hdr, trans_id
def _validate_resp_hdr(self,
response: bytearray,
trans_id: int,
slave_addr: int,
function_code: int,
count: bool = False) -> bytes:
"""
Validate the response header.
:param response: The response
:type response: bytearray
:param trans_id: The transaction identifier
:type trans_id: int
:param slave_addr: The slave identifier
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param count: The count
:type count: bool
:returns: Modbus response content
:rtype: bytes
"""
rec_tid, rec_pid, rec_len, rec_uid, rec_fc = struct.unpack(
'>HHHBB', response[:Const.MBAP_HDR_LENGTH + 1])
if (trans_id != rec_tid):
raise ValueError('wrong transaction ID')
if (rec_pid != 0):
raise ValueError('invalid protocol ID')
if (slave_addr != rec_uid):
raise ValueError('wrong slave ID')
if (rec_fc == (function_code + Const.ERROR_BIAS)):
raise ValueError('slave returned exception code: {:d}'.
format(rec_fc))
hdr_length = (Const.MBAP_HDR_LENGTH + 2) if count else \
(Const.MBAP_HDR_LENGTH + 1)
return response[hdr_length:]
def _send_receive(self,
slave_addr: int,
modbus_pdu: bytes,
count: bool) -> bytes:
"""
Send a modbus message and receive the reponse.
:param slave_addr: The slave identifier
:type slave_addr: int
:param modbus_pdu: The modbus PDU
:type modbus_pdu: bytes
:param count: The count
:type count: bool
:returns: Modbus data
:rtype: bytes
"""
mbap_hdr, trans_id = self._create_mbap_hdr(slave_addr=slave_addr,
modbus_pdu=modbus_pdu)
self._sock.send(mbap_hdr + modbus_pdu)
response = self._sock.recv(256)
modbus_data = self._validate_resp_hdr(response=response,
trans_id=trans_id,
slave_addr=slave_addr,
function_code=modbus_pdu[0],
count=count)
return modbus_data
class TCPServer(object):
"""Modbus TCP host class"""
def __init__(self):
self._sock = None
self._client_sock = None
self._is_bound = False
@property
def is_bound(self) -> bool:
"""
Get the IP and port binding status
:returns: True if bound to IP and port, False otherwise
:rtype: bool
"""
return self._is_bound
def get_is_bound(self) -> bool:
"""
Get the IP and port binding status, legacy support.
:returns: True if bound to IP and port, False otherwise
:rtype: bool
"""
return self._is_bound
def bind(self,
local_ip: str,
local_port: int = 502,
max_connections: int = 10):
"""
Bind IP and port for incomming requests
:param local_ip: IP of this device listening for requests
:type local_ip: str
:param local_port: Port of this device
:type local_port: int
:param max_connections: Number of maximum connections
:type max_connections: int
"""
if self._client_sock:
self._client_sock.close()
if self._sock:
self._sock.close()
self._sock = socket.socket()
# print(socket.getaddrinfo(local_ip, local_port))
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
self._sock.bind(socket.getaddrinfo(local_ip, local_port)[0][-1])
self._sock.listen(max_connections)
self._is_bound = True
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
"""
Send Modbus Protocol Data Unit to slave
:param modbus_pdu: The Modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
"""
size = len(modbus_pdu)
fmt = 'B' * size
adu = struct.pack('>HHHB' + fmt, self._req_tid, 0, size + 1, slave_addr, *modbus_pdu)
self._client_sock.send(adu)
def send_response(self,
slave_addr: int,
function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed
:type signed: bool
"""
modbus_pdu = functions.response(function_code,
request_register_addr,
request_register_qty,
request_data,
values,
signed)
self._send(modbus_pdu, slave_addr)
def send_exception_response(self,
slave_addr: int,
function_code: int,
exception_code: int) -> None:
"""
Send an exception response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
"""
modbus_pdu = functions.exception_response(function_code,
exception_code)
self._send(modbus_pdu, slave_addr)
def _accept_request(self,
accept_timeout: float,
unit_addr_list: list) -> Union[Request, None]:
"""
Accept, read and decode a socket based request
:param accept_timeout: The socket accept timeout
:type accept_timeout: float
:param unit_addr_list: The unit address list
:type unit_addr_list: list
"""
self._sock.settimeout(accept_timeout)
new_client_sock = None
try:
new_client_sock, client_address = self._sock.accept()
except OSError as e:
if e.args[0] != 110: # 110 = timeout expired
raise e
if new_client_sock is not None:
if self._client_sock is not None:
self._client_sock.close()
self._client_sock = new_client_sock
# recv() timeout, setting to 0 might lead to the following error
# "Modbus request error: [Errno 11] EAGAIN"
# This is a socket timeout error
self._client_sock.settimeout(0.5)
if self._client_sock is not None:
try:
req = self._client_sock.recv(128)
if len(req) == 0:
return None
req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]
self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)
req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]
except OSError:
# MicroPython raises an OSError instead of socket.timeout
# print("Socket OSError aka TimeoutError: {}".format(e))
return None
except Exception:
# print("Modbus request error:", e)
self._client_sock.close()
self._client_sock = None
return None
if (req_pid != 0):
# print("Modbus request error: PID not 0")
self._client_sock.close()
self._client_sock = None
return None
if ((unit_addr_list is not None) and (req_uid_and_pdu[0] not in unit_addr_list)):
return None
try:
return Request(self, req_uid_and_pdu)
except ModbusException as e:
self.send_exception_response(req[0],
e.function_code,
e.exception_code)
return None
def get_request(self,
unit_addr_list: Optional[list] = None,
timeout: int = None) -> Union[Request, None]:
"""
Check for request within the specified timeout
:param unit_addr_list: The unit address list
:type unit_addr_list: Optional[list]
:param timeout: The timeout
:type timeout: int
:returns: A request object or None.
:rtype: Union[Request, None]
:raises Exception: If no socket is configured and bound
"""
if self._sock is None:
raise Exception('Modbus TCP server not bound')
if timeout > 0:
start_ms = time.ticks_ms()
elapsed = 0
while True:
if self._client_sock is None:
accept_timeout = None if timeout is None else (timeout - elapsed) / 1000
else:
accept_timeout = 0
req = self._accept_request(accept_timeout, unit_addr_list)
if req:
return req
elapsed = time.ticks_diff(start_ms, time.ticks_ms())
if elapsed > timeout:
return None
else:
return self._accept_request(0, unit_addr_list)
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Fake classes of typing module.
https://github.com/micropython/micropython-lib/issues/190
https://github.com/micropython/micropython-lib/blob/3d779b8ceab5b65b9f70accbcbb15ab3509eceb7/typing/typing.py
"""
class _Subscriptable():
def __getitem__(self, item):
return None
_subscriptable = _Subscriptable()
class Any:
pass
class NoReturn:
pass
class ClassVar:
pass
Union = _subscriptable
Optional = _subscriptable
class Generic:
pass
class NamedTuple:
pass
class Hashable:
pass
class Awaitable:
pass
class Coroutine:
pass
class AsyncIterable:
pass
class AsyncIterator:
pass
class Iterable:
pass
class Iterator:
pass
class Reversible:
pass
class Sized:
pass
class Container:
pass
class Collection:
pass
# class Callable:
# pass
Callable = _subscriptable
class AbstractSet:
pass
class MutableSet:
pass
class Mapping:
pass
class MutableMapping:
pass
class Sequence:
pass
class MutableSequence:
pass
class ByteString:
pass
Tuple = _subscriptable
List = _subscriptable
class Deque:
pass
class Set:
pass
class dict_keys:
pass
class FrozenSet:
pass
class MappingView:
pass
class KeysView:
pass
class ItemsView:
pass
class ValuesView:
pass
class ContextManager:
pass
class AsyncContextManager:
pass
Dict = _subscriptable
class DefaultDict:
pass
class Counter:
pass
class ChainMap:
pass
class Generator:
pass
class AsyncGenerator:
pass
class Type:
pass
def cast(typ, val):
return val
def _overload_dummy(*args, **kwds):
"""Helper for @overload to raise when called."""
raise NotImplementedError(
"You should not call an overloaded function. "
"A series of @overload-decorated functions "
"outside a stub module should always be followed "
"by an implementation that is not @overload-ed."
)
def overload():
return _overload_dummy
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
__version_info__ = ("2", "3", "7")
__version__ = '.'.join(__version_info__)
+88
View File
@@ -0,0 +1,88 @@
# wget http://file.ofs.com/hv/script/umqtt/mqtt.py script/umqtt/mqtt.py
# mqtt_client.py 测试
from script.umqtt.simple import MQTTClient
from binascii import hexlify
import machine
import _thread
import time, sys
class MQTTClientThread:
def __init__(self, server, client_id):
self.server = server
self.client_id = client_id
self.running = False
self.send_list = []
self.receive_list = []
self.lock = _thread.allocate_lock()
self.client = MQTTClient(client_id, server)
def sub_cb(self, topic, msg):
with self.lock:
self.receive_list.append((topic, msg)) # 将接收到的消息添加到接收列表
print("Received: {}".format((topic, msg)))
def run(self):
try:
self.client.set_callback(self.sub_cb)
self.client.connect()
print("Connected to {}".format(self.server))
for topic in self.sub_list:
self.client.subscribe(topic)
self.running = True
while self.running:
self.client.check_msg()
self.process_messages()
print("mqtt exit")
except Exception as e:
sys.print_exception(e)
finally:
_thread.exit()
self.client.disconnect()
print("mqtt stop")
def process_messages(self):
with self.lock:
while self.send_list:
topic, msg, qos = self.send_list.pop(0) # 从发送列表中取出第一个消息
self.client.publish(topic, msg, qos)
# print("Sent: {} to topic: {} with QoS: {}".format(msg, topic, qos))
def start(self):
if not self.running:
_thread.stack_size(18192)
_thread.start_new_thread(self.run, ())
def stop(self):
self.running = False
def send_message(self, topic, message, qos=0):
with self.lock:
self.send_list.append((topic, message, qos)) # 将消息添加到发送列表
# print("Queued for sending: {}".format((topic, message, qos)))
def take_message(self):
with self.lock:
if self.receive_list:
return self.receive_list.pop(0) # 返回并移除接收列表的第一个消息
else:
return None # 如果没有消息,返回 None
def start_mqtt_client(params={}):
server = params['broker']['ip']
client_id = params['broker']['clientid'] + hexlify(machine.unique_id()).decode()[0:8]
mqtt_client = MQTTClientThread(server, client_id)
mqtt_client.client.port = params['broker']['port']
mqtt_client.client.user = params['broker']['user']
mqtt_client.client.pswd = params['broker']['passwd']
mqtt_client.sub_list = params['topic']['sub']
mqtt_client.start()
return mqtt_client
+220
View File
@@ -0,0 +1,220 @@
import socket
import struct
from binascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(
self,
client_id,
server,
port=0,
user=None,
password=None,
keepalive=0,
ssl=None,
ssl_params={},
):
if port == 0:
port = 8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.server = server
self.port = port
self.ssl = ssl
self.ssl_params = ssl_params
self.pid = 0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
self.sock.write(s)
def _recv_len(self):
n = 0
sh = 0
while 1:
b = self.sock.read(1)[0]
n |= (b & 0x7F) << sh
if not b & 0x80:
return n
sh += 7
def set_callback(self, f):
self.cb = f
def set_last_will(self, topic, msg, retain=False, qos=0):
assert 0 <= qos <= 2
assert topic
self.lw_topic = topic
self.lw_msg = msg
self.lw_qos = qos
self.lw_retain = retain
def connect(self, clean_session=True, timeout=None):
self.sock = socket.socket()
self.sock.settimeout(timeout)
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
if self.ssl is True:
# Legacy support for ssl=True and ssl_params arguments.
import ssl
self.sock = ssl.wrap_socket(self.sock, **self.ssl_params)
elif self.ssl:
self.sock = self.ssl.wrap_socket(self.sock, server_hostname=self.server)
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz = 10 + 2 + len(self.client_id)
msg[6] = clean_session << 1
if self.user:
sz += 2 + len(self.user) + 2 + len(self.pswd)
msg[6] |= 0xC0
if self.keepalive:
assert self.keepalive < 65536
msg[7] |= self.keepalive >> 8
msg[8] |= self.keepalive & 0x00FF
if self.lw_topic:
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
msg[6] |= self.lw_retain << 5
i = 1
while sz > 0x7F:
premsg[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
premsg[i] = sz
self.sock.write(premsg, i + 2)
self.sock.write(msg)
# print(hex(len(msg)), hexlify(msg, ":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
raise MQTTException(resp[3])
return resp[2] & 1
def disconnect(self):
self.sock.write(b"\xe0\0")
self.sock.close()
def ping(self):
self.sock.write(b"\xc0\0")
def publish(self, topic, msg, retain=False, qos=0):
pkt = bytearray(b"\x30\0\0\0")
pkt[0] |= qos << 1 | retain
sz = 2 + len(topic) + len(msg)
if qos > 0:
sz += 2
assert sz < 2097152
i = 1
while sz > 0x7F:
pkt[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
pkt[i] = sz
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt, i + 1)
self._send_str(topic)
if qos > 0:
self.pid += 1
pid = self.pid
struct.pack_into("!H", pkt, 0, pid)
self.sock.write(pkt, 2)
self.sock.write(msg)
if qos == 1:
while 1:
op = self.wait_msg()
if op == 0x40:
sz = self.sock.read(1)
assert sz == b"\x02"
rcv_pid = self.sock.read(2)
rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
if pid == rcv_pid:
return
elif qos == 2:
assert 0
def subscribe(self, topic, qos=0):
assert self.cb is not None, "Subscribe callback is not set"
pkt = bytearray(b"\x82\0\0\0")
self.pid += 1
struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt)
self._send_str(topic)
self.sock.write(qos.to_bytes(1, "little"))
while 1:
op = self.wait_msg()
if op == 0x90:
resp = self.sock.read(4)
# print(resp)
assert resp[1] == pkt[2] and resp[2] == pkt[3]
if resp[3] == 0x80:
raise MQTTException(resp[3])
return
# Wait for a single incoming MQTT message and process it.
# Subscribed messages are delivered to a callback previously
# set by .set_callback() method. Other (internal) MQTT
# messages processed internally.
def wait_msg(self):
res = self.sock.read(1)
self.sock.setblocking(True)
if res is None:
return None
if res == b"":
raise OSError(-1)
if res == b"\xd0": # PINGRESP
sz = self.sock.read(1)[0]
assert sz == 0
return None
op = res[0]
if op & 0xF0 != 0x30:
return op
sz = self._recv_len()
topic_len = self.sock.read(2)
topic_len = (topic_len[0] << 8) | topic_len[1]
topic = self.sock.read(topic_len)
sz -= topic_len + 2
if op & 6:
pid = self.sock.read(2)
pid = pid[0] << 8 | pid[1]
sz -= 2
msg = self.sock.read(sz)
self.cb(topic, msg)
if op & 6 == 2:
pkt = bytearray(b"\x40\x02\0\0")
struct.pack_into("!H", pkt, 2, pid)
self.sock.write(pkt)
elif op & 6 == 4:
assert 0
return op
# Checks whether a pending message from server is available.
# If not, returns immediately with None. Otherwise, does
# the same processing as wait_msg.
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
+1
View File
@@ -0,0 +1 @@
wget http://file.ofs.com/hv/main.py main.py