relay.c
Go to the documentation of this file.
1 /*******************************************************************************
2  * Copyright (C) 2019 Moxa Inc. All rights reserved.
3  * SPDX-License-Identifier: Apache-2.0
4  *
5  * Relay Sample Application
6  *
7  * Date Author Comment
8  * 2019-01-17 Wanhan Hsieh Created it.
9  ******************************************************************************/
10 
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <iothinx/iothinxio.h>
48 
50 int main(int argc, char **const argv)
51 {
52  int32_t rc;
53  uint32_t relay_slot = 3;
54  uint8_t relay_channel = 0;
55  uint32_t relay_values = 0;
56  uint32_t relay_count = 0;
57  char ch;
58 
59  while (-1 != (rc = getopt(argc, argv, "c:hs:")))
60  {
61  switch (rc)
62  {
63  case 's':
64  relay_slot = atoi(optarg);
65  break;
66  case 'c':
67  relay_channel = atoi(optarg);
68  break;
69  case 'h':
70  default:
71  printf("Relay sample program.\n\n");
72  printf("Usage: ./relay [OPTIONS]\n\n");
73  printf("Options:\n");
74  printf("\t%-8s Slot of relay module. Default slot = %d\n", "-s", relay_slot);
75  printf("\t%-8s Relay channel. Default channel = %d\n", "-c", relay_channel);
76  printf("\n");
77  return 0;
78  }
79  }
80 
81  printf("Relay slot = %lu\n", relay_slot);
82  printf("Relay channel = %u\n", relay_channel);
83 
84  // initialize ioThinx I/O
86  if (rc != IOTHINX_ERR_OK)
87  {
88  printf("ioThinx_IO_Client_Init() = %d\n", rc);
89  return -1;
90  }
91 
92  rc = ioThinx_Relay_GetValues(relay_slot, &relay_values);
93  if (rc != IOTHINX_ERR_OK)
94  {
95  printf("ioThinx_Relay_GetValues() = %d\n", rc);
96  }
97 
98  // set value
99  do
100  {
101  // invert relay value
102  if (relay_values & (0x1 << relay_channel))
103  {
104  relay_values &= ~(0x1 << relay_channel);
105  }
106  else
107  {
108  relay_values |= 0x1 << relay_channel;
109  }
110 
111  rc = ioThinx_Relay_SetValues(relay_slot, relay_values);
112  if (rc != IOTHINX_ERR_OK)
113  {
114  printf("ioThinx_DO_GetValues() = %d\n", rc);
115  }
116  printf("[%lu:%u] relay value = %x\n", relay_slot, relay_channel, (relay_values >> relay_channel) & 0x1);
117 
118  rc = ioThinx_Relay_GetCurrentCounts(relay_slot, relay_channel, 1, &relay_count);
119  if (rc != IOTHINX_ERR_OK)
120  {
121  printf("ioThinx_Relay_GetCurrentCounts() = %d\n", rc);
122  }
123  printf("[%lu:%u] relay count = %lu\n", relay_slot, relay_channel, relay_count);
124  ch = getchar();
125  }
126  while (ch != 'q');
127 
128  return 0;
129 }
IOTHINX_ERR ioThinx_Relay_GetCurrentCounts(uint32_t slot, uint8_t start, uint8_t count, uint32_t buf[])
IOTHINX_ERR ioThinx_Relay_GetValues(uint32_t slot, uint32_t *p_values)
#define IOTHINX_ERR_OK
Definition: iothinxio.h:35
IOTHINX_ERR ioThinx_Relay_SetValues(uint32_t slot, uint32_t values)
int main(int argc, char **const argv)
Definition: relay.c:50
IOTHINX_ERR ioThinx_IO_Client_Init(void)