how to read data from serial port in php

Solutions on MaxInterview for how to read data from serial port in php by the best coders in the world

showing results for - "how to read data from serial port in php"
Luis
09 Jan 2021
1
2For Windows the Example 1 looks same this one:
3
4<?php
5
6exec('mode com1: baud=9600 data=8 stop=1 parity=n xon=on');
7// execute 'help mode' in command line of Windows for help
8
9$fd = dio_open('com1:', O_RDWR);
10
11while (1) {
12
13  $data = dio_read($fd, 256);
14
15  if ($data) {
16     echo $data;
17  }
18}
19
20?>
21
22
Michele
23 Aug 2019
1<?php
2class Scanner {
3  protected $port; // port path, e.g. /dev/pts/5
4  protected $fd; // numeric file descriptor
5  protected $base; // EventBase
6  protected $dio; // dio resource
7  protected $e_open; // Event
8  protected $e_read; // Event
9
10  public function __construct ($port) {
11    $this->port = $port;
12    $this->base = new EventBase();
13  }
14
15  public function __destruct() {
16    $this->base->exit();
17
18    if ($this->e_open)
19      $this->e_open->free();
20    if ($this->e_read)
21      $this->e_read->free();
22    if ($this->dio)
23      dio_close($this->dio);
24  }
25
26  public function run() {
27    $stream = fopen($this->port, 'rb');
28    stream_set_blocking($stream, false);
29
30    $this->fd = EventUtil::getSocketFd($stream);
31    if ($this->fd < 0) {
32      fprintf(STDERR, "Failed attach to port, events: %d\n", $events);
33      return;
34    }
35
36    $this->e_open = new Event($this->base, $this->fd, Event::WRITE, [$this, '_onOpen']);
37    $this->e_open->add();
38    $this->base->dispatch();
39
40    fclose($stream);
41  }
42
43  public function _onOpen($fd, $events) {
44    $this->e_open->del();
45
46    $this->dio = dio_fdopen($this->fd);
47    // Call other dio functions here, e.g.
48    dio_tcsetattr($this->dio, [
49      'baud' => 9600,
50      'bits' => 8,
51      'stop'  => 1,
52      'parity' => 0
53    ]);
54
55    $this->e_read = new Event($this->base, $this->fd, Event::READ | Event::PERSIST,
56      [$this, '_onRead']);
57    $this->e_read->add();
58  }
59
60  public function _onRead($fd, $events) {
61    while ($data = dio_read($this->dio, 1)) {
62      var_dump($data);
63    }
64  }
65}
66
67// Change the port argument
68$scanner = new Scanner('/dev/pts/5');
69$scanner->run();
70